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?
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
It's Dispose method is invoked.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.