4

Spotted this oddity today in the reference source for the .NET Framework and I'm wondering if the answer will lead to an interesting edge case in the implementation.

The implementation of Enum.CompareTo() includes the explicit check this==null:

public int CompareTo(Object target)
{
    // ... elided ...
    if (this == null)
        throw new NullReferenceException();
    Contract.EndContractBlock();
    // ... elided ...
}

Full source: http://referencesource.microsoft.com/mscorlib/system/enum.cs.html#b50f2b9e3118e0d6

Why does this code need to check for null itself?

I'd have expected the runtime itself to take care of this - and indeed have written a lot of code under that assumption.

Bevan
  • 43,618
  • 10
  • 81
  • 133
  • probably because it was written "in the beginning" before generics, so the method cannot have a `struct` generic constraint, so as you indicate, it accepts anything as its input, and that input *could* be `null`. I guess I could ask, why *wouldn't* it need to check for `null`? – Dave Cousineau Sep 22 '16 at 00:27
  • 2
    This would seem similar to http://stackoverflow.com/questions/3143498/why-check-this-null – kiwidev Sep 22 '16 at 00:27
  • Thanks for the link - I failed to find it during my search. I wonder if there's anything specific to `Enum` (given that it supports the **enum** keyword and that those are value not reference types), but that link gives me enough information. – Bevan Sep 22 '16 at 03:35

0 Answers0