tags:

views:

217

answers:

2

I'm trying to sort an ArrayList of custom items and get 'At least one object must implement IComparable.' despite having implemented the IComparable interface for them. I'm just calling the default Sort() no parameters or anything. The definition of the object I'm trying to sort is as follows:

class AssetItem : System.IComparable<AssetItem>
{
        public string AssetName { get; set; }
        public int AssetID { get; set; }

        public int CompareTo(AssetItem item)
        {
            if (null == item)
            {
                return 1;
            }
            else if (this.AssetID < item.AssetID)
            {
                return -1;
            }
            else if (this.AssetID == item.AssetID)
            {
                return this.AssetName.CompareTo(item.AssetName);
            }
            else
            {
                return 1;
            }
        }

This code builds just fine. One more thing to keep in mind, and I suspect this may be the issue though I don't understand how, the class above is an inner class. If that is what's tripping me up, how would you go about comparing an inner class?

+7  A: 

You've implemented IComparable<T>, not IComparable. They're different interfaces. If you're going to use generics, just use List<T> to start with. I mean you could also implement IComparable, but I'd just move away from the somewhat-obsolete nongeneric collections if I were you.

Jon Skeet
Doh, that was a nobrainer. Thanks for the help though!
Trajanus
I had the same problem, thanks! It makes me wonder though, why doesn't IComparable<T> inherit from IComparable?
jrummell
@jrummell: That would force it to try to compare itself with *any* object, instead of just objects of the right type, which is a bit of a pain.
Jon Skeet
+3  A: 

Can you use LINQ in your project? If so, and if all you need is sorting by a property, you don't need to implement IComparable. You could just do:

theAssetsList.OrderBy(asset => asset.AssetId);
Konamiman