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???