Tutorial :Will dispose be called for anonymous variables?


For example,

int myResult= (new UnmanagedResourceUsingMemorySuckingPig()).GetThingsDone(id);  

There is no using block, no obvious way to use a using block, no obvious way to call Dispose(). And of course UnmanagedResourceUsingMemorySuckingPig does implement IDisposable.


If the finalizer of that class calls Dispose(), yes. If not, no.

(edit) Just some additional info:

Do not assume that Dispose will be called. Unmanaged resources owned by a type should also be released in a Finalize method in the event that Dispose is not called.


To clarify the above edit, I have seen many people (in this thread, on SO, and elsewhere) claim that "The GC will call Dispose() when the object is removed." This is not the case at all. Yes, a good, defensive coder writing a component will assume that Dispose() won't be called explicitly and does so in the finalizer. However, a good, defensive coder USING a component must assume that the finalizer does NOT call Dispose(). There is no automatic calling of Dispose() in the garbage collector. This functionality is ONLY in place if the finalizer calls Dispose().


I don't believe so. You'll have to write:

 using (UnmanagedResourceUsingMemorySuckingPig urumsp = new UnmanagedResourceUsingMemorySuckingPig())   {    myResult= urumsp.GetThingsDone(id);  }  


You can only be sure that if it has a Finalizer (destructor) then that will be called. A finalizer may call Dispose() but the usual implementation is that both the finalizer and Dispose() call protected Dispose(bool).

In other words, it depends on the implementation of UnmanagedResourceUsingMemorySuckingPig , if it follows the guidelines then the anonymous object will be cleaned up, but not as efficiently as with a using block.


No. However, the GC will eventually collect the object and notice that it is finalizable (it is finalizable, right?) and will finalize it for you. Dispose is for deterministically cleaning up resources.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »