Getting an exception when trying to use extension method with SortedDictionary... why?

Posted by Polaris878 on Stack Overflow See other posts from Stack Overflow or by Polaris878
Published on 2010-05-10T20:13:43Z Indexed on 2010/05/10 20:24 UTC
Read the original article Hit count: 242

Filed under:
|
|

I'm trying to place custom objects into a sorted dictionary... I am then trying to use an extension method (Max()) on this sorted dictionary. However, I'm getting the exception: "At least one object must implement IComparable". I don't understand why I'm getting that, as my custom object obviously implements IComparable. Here is my code:

public class MyDate : IComparable<MyDate>
{
    int IComparable<MyDate>.CompareTo(MyDate obj)
    {
        if (obj != null)
        {
            if (this.Value.Ticks < obj.Value.Ticks)
            {
                return 1;
            }
            else if (this.Value.Ticks == obj.Value.Ticks)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }
    }

    public MyDate(DateTime date)
    {
        this.Value = date;
    }

    public DateTime Value;
}


class Program
{
    static void Main(string[] args)
    {
        SortedDictionary<MyDate, int> sd = new SortedDictionary<MyDate,int>();

        sd.Add(new MyDate(new DateTime(1)), 1);
        sd.Add(new MyDate(new DateTime(2)), 2);

       Console.WriteLine(sd.Max().Value);   // Throws exception!!  
    }
}

What on earth am I doing wrong???

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET