5

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

HerpDerpington
  • 3,751
  • 4
  • 27
  • 43
  • The ?? operator is syntactic sugar, you are seeing what the compiler is translating it into. – Ron Beyer Sep 12 '15 at 14:58
  • @RonBeyer But the output is not correct, is it? – HerpDerpington Sep 12 '15 at 15:02
  • 3
    Can you post the raw IL? It would probably be a lot clearer if you saw what the reflector was trying to translate from. Usually I find that JetBrains DotPeek is a little more accurate than Redgate's, and I'm opposed to using Redgate after they "promised" to keep Reflector free, then started charging outrageously for it. DotPeek is free. – Ron Beyer Sep 12 '15 at 15:04
  • ILSpy is a free Reflector clone that is pretty awesome. There's even a port of the Reflexil plugin for it to let you edit the IL of the assembly. – Brandon Sep 12 '15 at 15:17
  • If compiled ?? is indistinguishable from if != null return then I guess there is nothing decompilers can do. – Andrey Sep 12 '15 at 15:19
  • I dont understand, can you tell me the difference between `return _queue ?? (_queue = new Queue(10));` and `return (this._queue = new Queue(10));`. i think the null-coalescing is redundant here. because both will set the `_queue` and will return it as result – M.kazem Akhgary Sep 12 '15 at 15:32
  • 2
    @M.kazemAkhgary The part after `??` will only execute if the part before is `null`. – Lasse V. Karlsen Sep 12 '15 at 15:34
  • Which version of .NET / Visual Studio / Compiler, and can you post a complete program that has this behavior? – Lasse V. Karlsen Sep 12 '15 at 15:35

1 Answers1

3

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536