Curious C# using statement expansion

前端 未结 5 979
一个人的身影
一个人的身影 2021-01-17 07:31

I\'ve run ildasm to find that this:

    using(Simple simp = new Simple())
    {
        Console.WriteLine(\"here\");
    }

generates IL cod

5条回答
  •  感动是毒
    2021-01-17 08:13

    The code must be translated this way to avoid possible NullReferenceException when disposing the object. As per C# language reference, the using statement accepts not only a local variable declaration as its first nonterminal resource_acquisition symbol, but any expression. Consider the following code:

    DisposableType @object = null;
    using(@object) {
        // whatever
    }
    

    Clearly, unless null-conditional @object?.Dispose() in the finnaly block, an exception would ensue. The null check is superfluous only when the expression is of a non-nullable value type (non-nullable struct). And indeed, according to the aforementioned language reference it is absent in such case.

提交回复
热议问题