If you aren't going to have to compare heterogeneous types for some reason, I would always recommend combining the generic and more general (eh, hmm "generic" would be the correct English word there, silly .NET terminology) non-generic approaches in one class, calling into the generic from the non-generic. Most generic sorts will favour the generic method, but the non-generic will be there for use with a non-generic type (e.g. ArrayList
) should it ever crop up. It's also a matter of 2 lines, and is logically sensible, so I don't hold with YAGNI in this case.
It's also a good idea to check for null arguments, even if you don't expect them. I've been caught a few times by failing to do so, and they could even be introduced "artificially" by some algorithms.
public class Class1Comparer : IComparer<Class1>, IComparer
{
public int Compare(Class1 x, Class1 y)
{
if(x == null)
return y == null ? 0 : -1;
if(y == null)
return 1;
return DateTime.Compare(x.myDate, y.myDate);
}
public int Compare(object x, object y)
{
//This has no type-checking because you said above it isn't needed. I would normally add some just in case.
return Compare((Class1)x, (Class1)y);
}
}