Due to a bug that was fixed in C# 4, the following program prints true
. (Try it in LINQPad)
void Main() { new Derived(); }
class Base {
public Base(Func<string> valueMaker) { Console.WriteLine(valueMaker()); }
}
class Derived : Base {
string CheckNull() { return "Am I null? " + (this == null); }
public Derived() : base(() => CheckNull()) { }
}
In VS2008 in Release mode, it throws an InvalidProgramException. (In Debug mode, it works fine)
In VS2010 Beta 2, it doesn't compile (I didn't try Beta 1); I learned that the hard way
Is there any other way to make this == null
in pure C#?
This observation has been posted on StackOverflow in another question earlier today.
Marc's great answer to that question indicates that according to the spec (section 7.5.7), you shouldn't be able to access
this
in that context and the ability to do so in C# 3.0 compiler is a bug. C# 4.0 compiler is behaving correctly according to the spec (even in Beta 1, this is a compile time error):The raw decompilation (Reflector with no optimizations) of the Debug mode binary is:
The CompilerGenerated method doesn't make sense; if you look at the IL (below), it's calling the method on a null string (!).
In Release mode, the local variable is optimized away, so it tries to push a non-existant variable on to the stack.
(Reflector crashes when turning it into C#)
EDIT: Does anyone (Eric Lippert?) know why the compiler emits the
ldloc
?I have had that! (and got proof too)
Not sure if this is what you are looking for
example: UserID = CheckForNull(Request.QueryString["UserID"], 147);
This isn't a "bug". This is you abusing the type system. You are never supposed to pass a reference to the current instance (
this
) to anyone within a constructor.I could create a similar "bug" by calling a virtual method within the base class constructor as well.
Just because you can do something bad doesn't mean its a bug when you get bit by it.
I could be wrong, but I'm pretty sure if your object is
null
there's never going to be a scenario wherethis
applies.For instance, how would you call
CheckNull
?