brian buck
brian buck

Reputation: 3454

Class Members and Using Statements

Suppose a class is defined:

class TestClass
{
    MemoryStream s = new MemorySteam();

    void DoStuff()
    {
        using (s = new MemoryStream())
        {
            // Do stuff
        }
    }
}

What happens to s when the using statement exits scope?

Edit: Will there be a problem using s in a different method?

Edit 2: Will there be an unreferenced object left undisposed from the first instantiation of MemoryStream?

Upvotes: 3

Views: 1261

Answers (3)

Justin Pihony
Justin Pihony

Reputation: 67065

It's Dispose method is called. (Note that it must implement the IDisposable interface so it can guarantee that Dispose is available)

The MSDN reference is pretty good IMO

Phil Haack also wrote an in depth article on this 7 years ago.

UPDATE TO YOUR EDIT

Once a method has had its dispose method called it will throw an exception if you try to use it outside of the scope of the method. So, yes it would be bad to reference it outside of the using. To be precise, it will throw an ObjectDisposedException

Upvotes: 7

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

Dispose method is called on objet in order to clean this object

We call using in order to clean non managed object, because they are not cleaned by GC

GC don't have informations about non managed object so developper must clean

Upvotes: 2

L.B
L.B

Reputation: 116098

It's Dispose method is invoked.

using Statement (C# Reference)

Upvotes: 6

Related Questions