0

Simple question. What is the difference between class destructor and dispose. Lets say in my class I have a RegistryKey, a COM object and some more things which needs to be disposed when class object is out of scope. I have code which does this, and I have put this both in destructor and dispose method. What is the best thing to use here.

public MyClass : IDisposable
{
    public ICOMObject SomeCOMObject;
    public RegistryKey registryKey;

    MyClass()
    { Initialize things; }

    ~MyClass()
    {
        ClearThings();
    }

    public void Dispose()
    {
        ClearThings();
    }

    private void ClearThings()
    {
        // Clear things.
    }
}
tanguy_k
  • 11,307
  • 6
  • 54
  • 58
fhnaseer
  • 7,159
  • 16
  • 60
  • 112
  • 1
    see this http://stackoverflow.com/questions/339063/what-is-the-difference-between-using-idisposable-vs-a-destructor-in-c – Bhupendra Jul 26 '13 at 06:49

1 Answers1

2

Difference: You cannot call a destructor explicitly. It will be called automatically when your object goes out of scope or program exits.

Dispose is a method on which you have control can be written seperately to dispose the managed and unmanaged resources in your object or is available when you implement the IDisposable interface. You can call it anytime you feel feasible to clear resources.

Regarding your question. Ideally you should dispose of any unmanaged resources explicity in the Dispose method. But you can also call the same method in Destructor (as a precautionary measure) as GC will not take care of these. Unless you dispose them off explicitly they will remain in memory.

Note: If you have decided to call the same method from both Destructor and Dispose then do check that object is not already disposed before calling dispose on the method you are disposing.

You can read more about destructors here

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Ehsan
  • 31,833
  • 6
  • 56
  • 65
  • Also: it is slightly better for performance to call Dispose(), or encapsulate your code in a using block. Letting the Garbage Collector run Finalize() (or your destructor) is slower. – Recipe Jul 26 '13 at 07:06