views:

43

answers:

4

Is outer reference-type object guaranteed to remain valid after assigned to inner object in nested "using" scope?

A x;
{
    using (A y = new A())
    {
        x = y;
    }
}
x.foo(); // Is x rock-solid, guaranteed to be still valid here, or is this iffy? i.e. will the call to x.foo() bomb or work only "by chance"?

I'm concerned because I came across 2 articles talking about premature garbage collection, though their situations are quite different: http://www.curly-brace.com/favorite.html http://www.theserverside.net/tt/articles/showarticle.tss?id=GarbageCollection

+3  A: 

Sort-of. Once you leave the using block, the Dispose method of the object will be called, but the object reference will still exist, so you can still call foo(). Any well-written object will likely throw an ObjectDisposedException if you try to access it after Dispose has been called.

Dean Harding
+3  A: 

The object x references will still be a valid object but it will have been disposed. It is not eligible for garbage colection, but it might not be in a usable state. Depending on the implementation, calling a method on the object may result in an ObjectDisposedException being thrown. Check the documentation for the specific class to see if this is the case.

Mark Byers
+1  A: 

It will be a valid reference to an object, but that object will have been disposed, and is likely unusable for any further activity (or if it has been written to allow itself to be resurrected after Dispose has been called, you'll probably have to manually Dispose it later).

Damien_The_Unbeliever
A: 

At the end of using scope Dispose is being called on the object. So the instance x refers to will be disposed.

Itay