Destroying Objects in C#

 

In C#, objects are going to release automatically by garbage collector(GC) after specific time. If you want to release objects manually use either Dispose() or finalizer() methods. To release the objects for user-defined class, particular class has to inherit IDisposable interface. 

 

Here we discuss about usage of Dispose() and Finalizer() methods.

 

Dispose(): 

If you want to explicitly release resources such as file handles, mutexes, and so on, you can provide a public function called Dispose or close, which will do this on demand. If you do write this function, you should call suppressFinalize() method if you have a finalizer method, so the GC does not try to free the resources twice. To use this method, you must inherit from IDisposable interface. If you have derived the class, make sure to call the base class Dispose() method.

 

Finalizer() method: 

The finalizer (~classname)method is called by the GC asynchronously when the object is being destroyed. It allows you to customize the destruction of the object when called by the GC. It is extremely important to remember that when you use this method, your object will always survive the first garbage collection and will not be freed until the next garbage collection cycle.

 

Caution Use the finalizer only to release unmanaged resources, and avoid doing this if you can. The order in which objects that have a finalizer are freed by the GC is not defined. This makes freeing managed resources in the finalizer dangerous. You can use performance Monitor counters to determine the effect of using finalizers in your code. Use FinalizationSurvivors to determine the unmanaged resources that are consuming memory. Use promoted Finalization-Memory from GenX to determine the number of bytes that were promoted to this generation.

 

As shown below, we have Employee class which inheriting the IDisposable interface.

 

using System;

 

namespace CSharpDisposeExp 

{ 

    class Employee : IDisposable 

    {

 

    } 

}