Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Comparing Object T

Geoff Orr makes a comment about how easy it is to implement IComparable so that items can be sorted in an arraylist.  I would like to extend this by saying that in .NET v2 there is an IComparable(of T) which you should also implement.  Something like this would work:

Public Overloads Function CompareTo(ByVal obj As Object) As Integer Implements IComparable.CompareTo
   If TypeOf obj Is CostCentre Then
     
Return CompareTo(CType(obj, CostCentre))
  
Else
     
Throw New ArgumentException("object is not a CostCentre")
   End If
End Function

Public Overloads Function CompareTo(ByVal costCentre As CostCentre) As Integer Implements IComparable(Of CostCentre).CompareTo
   Return Me.mCostCentreDesc.CompareTo(costCentre.CostCentreDesc)
End Function

I must admit that I'd prefer to use the C# anonymous method to implement sorting on an as needed basis.  For example:

List<CostCentre> lst = new List<CostCentre>();
lst.Sort(
delegate(CostCentre x, CostCentre y)
               {
return x.Description.CompareTo(y.Description);}
           
);

Comments are closed