Franki1986
Franki1986

Reputation: 1436

Does using dispose objects if they are declared in a method

Let's say I create a disposable object in a method, but I will call a using out of the method. Is then everything disposed in this method?

using(DbConnection connection = new DbConnection("myConnection"){

   SomeMethod();
}


public void SomeMethod(){
    var stream = new MemoryStream()
    // ... Do something with the stream ... 
}

Is the stream created in the 'SomeMethod' then disposed?

Upvotes: 1

Views: 52

Answers (2)

Mukesh Methaniya
Mukesh Methaniya

Reputation: 772

when we use Using keyword,it will call dispose method of object which is created in using(Form m =new Form()) bracket. so remember we have to dispose manually if anything to dispose in the scope which is defined by {}

Example:

using(Form test =new Form())//test object will disposed by using at end of scope 
{//Scope start

//code written here or created new object are not disposed by using

//Scope End
}

Upvotes: 0

Rob
Rob

Reputation: 27357

No, it won't be. Only the reference explicitly specified in the using statement will be disposed.

In this case, only connection will be disposed after the code execution leaves the using block. You'll need to also wrap var stream = .. in a using block, or manually dispose it.

Upvotes: 2

Related Questions