Ran into a really interesting gotcha some time ago and ran into it again. It was rather irritating to go back and try to find the magical "how did I fix this?" so posting it was a good idea, and this is a great example of how something that makes perfect sense in code would produce a really strange, inconsistant "error" that you wouldn't expect.
So let's say you have a base class and there's a nullable datetime in there, "LastUpdatedDate" along with a nullable "CreatedDate" and a host of other junk that we don't care about right now. The request is to retrieve the most recently updated item and at your disposal is a list of these items, we'll call it List<entry> entries.
entries.Sort(delegate(Enty entry1, Entry entry2)
{
return entry2.LastUpdatedDate.Value.CompareTo(entry1.LastUpdatedDate.Value);
});
Well, bad news -- the LastUpdatedDate are equal. How do you know when which entry comes out on top? Did you say "that will never happen because of ticks, they will never be equal" ...not quite. It's created on a database that you have no control over, IE its created on a trigger. I ended up adding in another bit of logic to produce a more reliable output. It isn't perfect. Incase you are not fimiliar with CompareTo -- it returns a 1, a 0 or a -1. 1 is greater than, 0 is equal, -1 is less than, so we insert some logic into our anonymous method...
entries.Sort(delegate(Enty entry1, Entry entry2)
{
int x = entry2.LastUpdatedDate.Value.CompareTo(entry1.LastUpdatedDate.Value);
if (x == 0)
return (entry2.CreatedDate.Value.CompareTo(entry1.CreatedDate.Value));
else return x;
});
It's still possible that created date and last updated date could be equal, but the possibility is greatly reduced (in this case anyway).