Recently I’ve been updating one of our older utilities to .NET 4. A few days ago I stumbled across this line of C#:
if(this == null) return null;
I was dumbfounded. When would that ever evaluate to true? Worse yet, why was it repeated in two other places?
Out of curiosity (read: late night boredom) I did some research to see if there’s ever a case where the condition would be met and found a good discussion over on Stack Overflow. There apparently are a few cases where
this == null could actually be
- Overload the == operator to explicitly return
truewhen comparing to
- Pass this to a base constructor as part of a closure.
Neither of these cases applied to this code. We weren’t overloading the
== operator and we certainly weren’t using it in a closure let alone a closure being passed to a base constructor. The second case has apparently been fixed for .NET 4 so it definitely wouldn’t apply with the changes I was making.
As part of the Stack Overflow discussion Eric Lippert provided an interesting comment about why the C# compiler doesn’t complain about checking for
this == null. He basically says that the compiler doesn’t complain because they didn’t think about it because it’s obviously wrong. So for those wondering, yes, I eliminated all three instances of this code from the utility.