I was working with ?? operator in C# 4 and found a interesting feature.
This line of code always assigns null to existingObject if it is already null regardless of the searchForObject() return value (searchForObject returns a not null object, in fact it is a linq statement not a function and if the following statement will be replaced with simple if construct then existingObject will be assigned a not null object):
existingObject = extstingObject ?? searchForObject();
Could someone explain why?
Here is a link to MSDN, it says:
A nullable type can contain a value, or it can be undefined. The ??
operator defines the default value to be returned when a nullable type
is assigned to a non-nullable type. If you try to assign a nullable
value type to a non-nullable value type without using the ?? operator,
you will generate a compile-time error. If you use a cast, and the
nullable value type is currently undefined, an
InvalidOperationException exception will be thrown.
The part about assigning a nullable type to a non-nullable type is not what I expected.
The problem was deferred initialization of local variables in the debugger of Visual Studio 2010.
Apart from what I said in this comment:
another question comes to mind – is
existingObjectreally null after the assignment? 🙂 How have you asserted that?Have a look at my question (and the answers):
Surprising CLR / JIT? behaviour – deferred initialization of a local variable