GOTO inside using block, will the object get disposed?

后端 未结 4 1683
我寻月下人不归
我寻月下人不归 2020-12-11 23:24

I\'m quite unsure about using goto inside an using block.

For example:

using(stream s = new stream(\"blah blah blah\"));
{
         


        
4条回答
  •  被撕碎了的回忆
    2020-12-11 23:36

    using(Stream s = new Stream("blah blah blah"))
    {    
        if(someCondition) goto myLabel;
    }
    

    equals to

    Stream s;
    try
    {
         s = new Stream("blah blah blah");
         if(someCondition) goto myLabel;
    }
    finally
    {
      if (s != null)
        ((IDisposable)s).Dispose();
    }
    

    So, as soon as you leave the using block, the finally block does happen, no matter what made it quit.

提交回复
热议问题