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?
operator??by modifying your return statement to bereturn query.DefaultIfEmpty(new MyClass()).First();MyClass _localMyClass = MyClassDAO.GetMyClassByID(123); _localMyClass = _localMyClass ?? new MyClass();) and stepping through it.