Curious C# using statement expansion

前端 未结 5 933
一个人的身影
一个人的身影 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 07:59

    No, the finally block will ALWAYS be executed. You may not be getting the object from a new but from some other function that returns your object - and it might return NULL. using() is your friend!

    dss539 was kind enough to suggest I include his note:

    using(Simple simp = null) 
    

    is yet another reason that the expansion must check for null first.

提交回复
热议问题