- class Employee : IComparable<Employee>{} means comparing an employee object with other employee object. Here, we can compare property or properties of two employees. It has very useful practical cases e.g. sorting employees by their names.
- class Employee : IComparable<Manager>{} means comparing an employee object with other manager object. Here, we can compare property or properties of an employee with a manager object. It has few practical cases.
- class Employee : IComparable{} means comparing an employee object with object type object. It is not type safe.
- class Employee : IComparable<string>{} means comparing an employee object with string type data. It does not make sense.
Example of IComparable<T>
class Employee : IComparable<Employee>
{
public string? Name { get; set; }
public int Age { get; set; }
public int CompareTo(Employee? other)
{
if (other == null || Name == null)
{
throw new ArgumentNullException("Name is null.");
}
else
{
return string.Compare(this.Name, other.Name, StringComparison.Ordinal);
}
}
}
class Program
{
static void Main(string[] args)
{
string[] cities = { "Delhi", "Agra", "Jaipur" };
Array.Sort(cities);
Employee[] employees = {
new Employee { Name = "Rajesh", Age = 21 } ,
new Employee { Name = "Ajay", Age = 23 },
new Employee { Name="Niraj",Age=31}
};
Console.WriteLine("---Before Sorting---");
foreach (var employee in employees)
{
Console.WriteLine($"Name: {employee.Name} Age:{employee.Age}");
}
Array.Sort<Employee>(employees);
Console.WriteLine("---After Sorting---");
foreach (var employee in employees)
{
Console.WriteLine($"Name: {employee.Name} Age:{employee.Age}");
}
}
}---Before Sorting---
Name: Rajesh Age:21
Name: Ajay Age:23
Name: Niraj Age:31
---After Sorting---
Name: Ajay Age:23
Name: Niraj Age:31
Name: Rajesh Age:21
Example of IComparable
You can see examples of non-generic IComparable at this post: Click here.
No comments:
Post a Comment