Building C# Comparable Objects: IComparable versus IComparer - Full Program
(Page 4 of 4 )
Here is the full program:
class Program
{
static void Main( string [] args)
{
Employee[] employees = new Employee[5];
employees[0] = new Employee( "Dan K." , 12456);
employees[1] = new Employee( "Jim L." , 99584);
employees[2] = new Employee( "Tony T." , 51472);
employees[3] = new Employee( "Lee W." , 32788);
employees[4] = new Employee( "Leda B." , 44110);
Array .Sort(employees);
PrintEmployees(employees);
Console .WriteLine();
Array .Sort(employees, Employee.SortByEmployeeName);
PrintEmployees(employees);
}
static void PrintEmployees(Employee[] employees)
{
foreach (Employee e in employees)
Console .WriteLine(e);
}
}
class Employee : IComparable
{
private string name;
public string Name
{
get { return name; }
set { name = value ; }
}
private int id;
public int Id
{
get { return id; }
set { id = value ; }
}
public Employee( string a_name, int an_id)
{
name = a_name;
id = an_id;
}
public override string ToString()
{
return string .Format( "Name: {0}ttId: {1}" ,
Name, Id);
}
public static IComparer SortByEmployeeName
{
get { return ( IComparer ) new EmployeeComparer(); }
}
#region IComparable Members
public int CompareTo( object obj)
{
Employee temp = (Employee)obj;
if ( this .Id > temp.Id)
return 1;
if ( this .Id < temp.Id)
return -1;
else
return 0;
}
#endregion
}
class EmployeeComparer : IComparer
{
public EmployeeComparer() { }
#region IComparer Members
public int Compare( object obj1, object obj2)
{
Employee e1 = (Employee)obj1;
Employee e2 = (Employee)obj2;
return string .Compare(e1.Name, e2.Name);
}
#endregion
}
Conclusion
The System.Array.Sort() methods sorts objects of different types. While sorting predefined types (string…) is already implemented in the language, sorting objects for classes that we create requires implementing interfaces to tell the runtime how to sort these objects. We can implement the Comparable interface and override its CompareTo() method and/or the Comparer interface with its Compare() method. The Sort() method is overloaded to support both implementations.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |