MatthewMartin
MatthewMartin

Reputation: 33143

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.

Upvotes: 3

Views: 846

Answers (4)

Kent Boogaart
Kent Boogaart

Reputation: 178680

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.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273274

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.

Upvotes: 1

Adam Robinson
Adam Robinson

Reputation: 185643

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.

Edit

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().

Upvotes: 10

Otávio Décio
Otávio Décio

Reputation: 74280

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

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

Upvotes: 4

Related Questions