Reputation: 111
I have this code:
MyClass _localMyClass = MyClassDAO.GetMyClassByID(123) ?? new MyClass();
This is the method:
public static MyClass GetMyClassByID(int id)
{
var query = from m in ctx.MyClass
where m.MyClassID == id
select m;
return query.FirstOrDefault<MyClass>();
}
So the FirstOrDefault()
doesn't find a hit in the entity framework context, which is the "ctx" object. So the 'default' value to be returned is null
, since the target of the query is a class.
The result of the first bit of code, using the ??
, results in _localMyClass
being what? I would say it would be the new MyClass()
. Instead, _localMyClass
ends up being null. I tried grouping the logic with various sets of parentheses, but still no luck.
Odder still; when I set a debug break point, and copy/paste the MyClassDAO.GetMyClassByID(123) ?? new MyClass()
into the watch screen of Visual Studio, the result is the new MyClass()
instead of null
.
Can anybody explain why it would be working in this manner? Why it doesn't recognize the method return value as null
and then instead use the new
part?
Upvotes: 5
Views: 882
Reputation: 393603
Ok, since the self-answer has already been accepted, a pro-forma answer in case anyone needs another possible case in the future:
FirstOrDefault()
will in fact return the default value which can be null
for object references, but cannot be that for value-types. If MyClass
is a valuetype (think: struct
) you'd be better of
MyClass?
nullable type (short for Nullable) $0.02
Upvotes: 1
Reputation: 111
After closing and reopening Visual Studio, the code worked fine.
I'm using Visual Studio Ultimate 2010 w/ service pack 1.
I have had this happen in the past, and should have remembered to try it first. I have noticed that VS seems to behave strangely sometimes, especially when running the web application in debug, specifically when running the web app locally (from my local IIS) and attaching to w3wp.exe.
Upvotes: 0
Reputation: 31606
Just a guess because I made this mistake before and it baffled me for the longest time.
Do you have a conditional breakpoint and in that conditional breakpoint do you have the condition as _localMyClass = null
?
One time I did something like that when I meant to write ==
in the conditional breakpoint and it resulted in the debugger setting the value to null. Similarly do you have any watch values that could be setting it to null?
Upvotes: 2