I have an object that has a disposable object as a member.
public class MyClass
{
private MyDisposableMember member;
public DoSomething
{
using (member = new MyDisposableMember())
{
// Blah...
}
}
}
There can be many methods in MyClass
, all requiring a using
statement. But what if I did this instead?
public class MyClass
{
private MyDisposableMember member = new MyDisposableMember();
public DoSomething
{
// Do things with member :)
}
~MyClass()
{
member.Dispose();
}
}
As you can see, member
is being disposed in the destructor. Would this work? Are there any problems with this approach?
Destructor implicitly calls the Finalize method, they are technically the same. Dispose is available with objects that implement the IDisposable interface. The destructor implicitly calls Finalize on the base class of the object.
It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessary. At runtime C#, C++ destructors are automatically converted to Finalize method. .
The destructor is a special member function which is invoked when an object is destroyed. It is the last method run by a class. The garbage collector is part of the framework, automatically manages memory, and non-deterministically collects unreferenced objects to avoid memory leaks.
The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
Ideally, Dispose() should have already been called prior to finalization. It would be better to follow the typical dispose pattern, and allow the user to Dispose() the object properly, and have the finalizer Dispose of it if dispose has not already been called.
In this case, since you're encapsulating an IDisposable, you really don't need to implement the finalizer at all, though. (At the the point of finalization, your encapsulated member will get finalized, so there's no need to finalize your object - it just adds overhead.) For details, read this blog article I wrote on encapsulating an IDisposable.
You should probably make MyClass
implement IDisposable
. Inside the Dispose()
method, call member.Dispose();
. That way the programmer can have control over when the member gets disposed.
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