Search code examples
c#null-coalescing-operator.net-reflectornull-coalescing

Is the .NET Reflector unable to reflect over the null-coalescing operator correctly?


I wrote this piece of code:

private Queue<int> EnsureQueue()
{
    return _queue ?? (_queue = new Queue<int>(10));
}

and the reflector gives me:

private Queue<int> EnsureQueue()
{
    if (this._queue == null)
    {
    }
    return (this._queue = new Queue<int>(10));
}

Obviously, this is not what the original code says. The line (this._queue = new Queue<int>(10)); will alway return a new Queue<int>(10) instead of _queue when it is not null.

Is this a bug in the .NET Reflector or am I missing something? The program seems to behave correctly...

EDIT -> See my answer


Solution

  • This is what my copy of Reflector makes of this method:

    private Queue<int> EnsureQueue()
    {
        return (this._queue ?? (this._queue = new Queue<int>(10)));
    }
    

    Looks pretty darn good to me. Version 8.5.0.179, be sure to update yours.