Search code examples
c#coalescenull-coalescing-operatornull-coalescing

C# coalesce operator doesn't replace a null method return value?


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?


Solution

  • 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.