I have seen so many times developers using a disposable object inline, here for instance. By inline I mean:
var result = new DataTable().Compute("1 + 4 * 7", null);
I know that the Dispose
method won't be called, but since no reference is held to the object, how will the garbage collector handle it? Is it safe to use a disposable object like that?
I used a DataTable
in my example because it is the only concrete example I found, but my question applies to disposable objects in general. I do not personally use them like that, I just wanted to know if they are handled diffently by the GC if they are used that way.
The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.
The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed." msdn.microsoft.com/en-us/library/… @HansPassant: If an object implements IDisposable , one can call (IDisposable.
The key problem here is the timing when Dispose
is called, which is just unknown in your example (providing a good implementation of IDisposable
— see below). I'd consider using an IDisposable
instance without a using
statement a code smell. The class is implementing IDisposable
for a reason, and thus you as a user should obey its contract.
However, note that in a correct implementation of IDisposable
the class'es finalizer handles the disposal of an un-disposed object. Hence even if not instantiated within a using
, the disposal shall be performed, but in unknown time and on a different (the GC's) thread.
I just wanted to know if they are handled diffently by the GC if they are used that way.
No, the GC treats all object alike and doesn't treat IDisposable
implementations anyhow differently. However, in a correct implemenetation of IDisposable
the Finalize
method (invoked by the GC on every object unless suppressed on a per-object basis) call would lead to invoking the Dispose
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With