Destructor,Finalizer and Dispose Method in .NET Framework

Destructor and Finalizer:

Destructor are called by the CLR when the Garbage Collector destroys an object. In VB.NET it is called the Finalize() method. In C# it is declared by putting a tilda '~' in front of the class name (~MyClass() {}). Destructors aren't the best place to put clean up code. This is because it is only called by the GC and you can't determine when it will be called (you can force it to be called, but that's not recommended).

Dispose:

The Dispose() method is simply a method you call manually to clean up yourobject. For this explicit clean up, .NET provides the dispose design pattern. Objects which need explicit clean up of unmanaged resources(connection object,File objects, etc..) implement the IDisposable interface. The IDisposable interface consists of the Dispose method, which unlike the Finalize method is under the control of the developer.

The recommended practice is to implement both Finalize as well as Dispose methods on an object which needs to clean up unmanaged resources. The Finalize method would serve as a backup mechanism in the event that the Dispose is never called. The garbage collector would perform the object finalization and prevent a permanent leak of the unmanaged resource.

No comments: