Search code examples
c#usinggoto

C# goto from using statement


Do

using and goto

statements dispose objects if the code looks similar to this?

public T MyMethod(){
     using(stream){
         //do some work here
         if(completed){
             //do some work
             goto next;
         }
         return something;
     }
   next:
     //do another work here...
     //is stream disposed?
}

Solution

  • Yes, it will be disposed. There's a similar question with an answer here: GOTO inside using block, will the object get disposed?

    By the way, I personally discourage the use of goto. You can achieve the same behaviour with if statements.