If you want a null
value to be treated as default(DateTime)
you could do something like this:
public class NullableDateTimeComparer : IComparer<DateTime?>
{
public int Compare(DateTime? x, DateTime? y)
{
return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault());
}
}
and use it like this
var myComparer = new NullableDateTimeComparer();
myComparer.Compare(left, right);
Another way to do this would be to make an extension method for Nullable
types whose values are comparable
public static class NullableComparableExtensions
{
public static int CompareTo<T>(this T? left, T? right)
where T : struct, IComparable<T>
{
return left.GetValueOrDefault().CompareTo(right.GetValueOrDefault());
}
}
Where you'd use it like this
DateTime? left = null, right = DateTime.Now;
left.CompareTo(right);