Generic Lists and Custom Classes

According to Microsoft generic collections are faster than collections of the object type. Its hard to argue when theory is on their side, a collection that can skip a cast saves time. Fact had another idea though. I’ve actually never been able to create a code using generic collections that is faster than a collection of the object type. If someone can prove me wrong then please let me know. But to be honest I’ve never used generic collections with speed in mind. It’s the error minimizing code that attracts.

By creating a generic list the compiler knows what type of object that the list contains and no cast is needed when extracting objects from the list. And no other objects than of the specified type can be inserted into the generic list.

SalesReport sr = new SalesReport();
List<SalesReport> sr_list = new List<SalesReport>();
sr = sr_list[0];

All types of custom classes can be used as a base to create a generic list. But not all custom classes can be used as they are if you are interested in using all the functionalities of a list. To be able to sort the list you either have to implement the interface IComparable in your custom class or you have to create your own sorting class implementing the interface IComparer. In this post we focus on the IComparable solution.

The problem with a custom class is that you most likely have several variables that can be used for comparison and no one except you knows which one to use. By implementing IComparable you also add the CompareTo method solving this little issue. In this method you implement the compairing part, the missing information.

public class SalesReport : IComparable 
    public string UnitName { get; set; }
    public double Amount { get; set; }

    public SalesReport(string _UnitName, double _Amount)
        this.UnitName = _UnitName;
        this.Amount = _Amount;

    public int CompareTo(object obj)
        SalesReport sr = (SalesReport)obj;
        return this.UnitName.CompareTo(sr.UnitName);

After having implemented IComparable it’s now possible to call the sort method of the generic list.

List<SalesReport> sr_list = new List<SalesReport>();
sr_list.Add(new SalesReport("A", 45.3));
sr_list.Add(new SalesReport("F", 13.5));
sr_list.Add(new SalesReport("C", 41.9));
sr_list.Add(new SalesReport("T", 28.0));
sr_list.Add(new SalesReport("B", 104.6));

It’s very easy and doesn’t take that much time to complete so why not make all your classes comparable?