Steve Mitcham
Steve Mitcham

Reputation: 5313

Will an implicit variable in a using clause be garbage collected?

In the following code, does the underlying code contain a hard reference to the unnamed variable instance of type Foo, or is the item vulnerable to garbage collection?

using(new Foo())
{
    // Something done here.
}

The collected item is just a semaphore type object that performs some reference counting on resources so it isn't being referenced in the code block.

Upvotes: 3

Views: 134

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 160922

using(new Foo())

this anonymous instance of Foo will go out of scope after the using block and may be garbage collected then.

Upvotes: 3

SLaks
SLaks

Reputation: 887657

The using clause creates a hidden locally-scoped variable holding the object (this variable is used by the generated finally clause).

This variable prevents the object from being GC'd.

You can see this variable in the spec.

Upvotes: 10

Related Questions