I am trying to work out a relatively clean way of comparing two types of DateTime? objects without having to bother with lots of null checking.
Is something like the following a good idea or is there a much simpler or sensible way to go about it;
DateTime? test = DateTime.MinValue;
DateTime? date1 = new DateTime(2008, 6, 1, 7, 47, 0);
if (string.Format("{0:MM/dd/yyyy}", date1) == string.Format("{0:MM/dd/yyyy}", test))
{
Console.WriteLine("They are the same");
}
else
{
Console.WriteLine("They are different");
}
No, using text formatting to compare simple values is not a good idea IMO. One option to make things neater would be to write an extension method to effectively propagate nulls (like a maybe monad):
You can then compare projections of nullable types easily:
Or even add your own equality projection method:
And:
This is much more flexible and elegant than performing a text conversion when you really don’t care about the text.