Reputation: 15039
Hi I have an object has is Disposable and I would like to know what is better:
this.object.Dispose();
or
this.object = null;
or
this.object.Dispose();
this.object = null;
Upvotes: 4
Views: 7675
Reputation: 747
Dispose is not better or worse than setting to null. They serve different purposes.
Because, if implemented correctly, the finalizer of the object should call the Dispose() method, most of the times you don't need to call it explicitly. As soon as there are no references to the object, the finalizer method is called by the garbage collector and consequently the Dispose method.
Upvotes: 2
Reputation: 32661
object.Dispose() or object = null
What is dispose? Any type that implements IDisposable has this method normally (though you can write your own public method).
public class Test:IDisposable
{
public void Dispose()
{
//release resources here managed and unmanaged
}
}
Now as you have implemented IDisposable so the best way is
using (Test t = new Test())
{
}
by doing this in using block framework will take care of all the resources. and you don't need to worry. And even if you the finalizer method on the object should be calling Dispose() for you
Though alternatively you can also do
Test t = new Test();
t.Dispose();
now what about setting it null?
Test t = new Test();
t = null;
The object it referenced is no longer accessible and can now be garbage-collected (managed resources). You have to handle the un-managed resources yourself.
Upvotes: 0
Reputation: 152501
You only need to Dispose
the object - you do not need to set it to null
, unless there is other code that checks for a null value and responds appropriately.
Upvotes: 2
Reputation: 223197
Dispose
is better, even more better approach would be to use the object inside the using
block and let the framework dispose it.
For: this.object.Dispose();
vs this.object = null;
Setting the object to null
may result in leaving out un-managed resources un-disposed. The whole object of having IDisposable
is to make sure that un-managed resources are disposed after their usage.
See: IDisposable - MSDN
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.
Upvotes: 12