destructors in c#
by ansil
introduction
in the enterprise application development world, the buzzwords areperformance, scalability, and security. i started my career as a vc++programmer, and one fine morning, i was transferred to web developmentdepartment. like every c++ programmer, i also was frustrated. i thoughtevery tom, dick, and our very own harry can program in html. but, sooni found that the real challenge is to produce high performance,scalable, and reliable applications. and above all that the looselycoupled, stateless nature of web environment is always going to hauntyou.
in order to produce high performance scalable applications, it isimportant to use your resources in an optimized manner. one tip is thatuse your resource as late as you can and free it at the earliest afteryour use. my intention here is to describe the object cleaning upmechanism used in c#.
destructors
as we all know, ‘destructors’ are used to destruct instances ofclasses. when we are using destructors in c#, we have to keep in mindthe following things:
a class can only have one destructor. destructors cannot be inherited or overloaded. destructors cannot be called. they are invoked automatically. a destructor does not take modifiers or have parameters.
the following is a declaration of a destructor for the class myclass:
~ myclass()
{
// cleaning up code goes here
}
the programmer has no control on when the destructor is going to beexecuted because this is determined by the garbage collector. thegarbage collector checks for objects that are no longer being used bythe application. it considers these objects eligible for destructionand reclaims their memory. destructors are also called when the programexits. when a destructor executes what is happening behind the scenesis that the destructor implicitly calls the object.finalize method on the objects base class. therefore, the preceding destructor code is implicitly translated to:
protected override void finalize()
{
try
{
// cleaning up .
}
finally
{
base.finalize();
}
}
now, let us look at an example of how destructors are called. we have three classes a, b and c. b is derived from a, and c is derived from b. each class has their own constructors and destructors. in the main of the class app, we create an object of c.
using system;
class a
{
public a()
{
console.writeline(“creating a”);
}
~a()
{
console.writeline(“destroying a”);
}
}
class b:a
{
public b()
{
console.writeline(“creating b”);
}
~b()
{
console.writeline(“destroying b”);
}
}
class c:b
{
public c()
{
console.writeline(“creating c”);
}
~c()
{
console.writeline(“destroying c”);
}
}
class app
{
public static void main()
{
c c=new c();
console.writeline(“object created “);
console.writeline(“press enter to destroy it”);
console.readline();
c=null;
//gc.collect();
console.read();
}
}
as we expect, the constructors of base classes will be executed andprogram will wait for the user to press enter. when this occurs, weset the object of class c to null.but the destructors are not executing ..!!?? as we already said, theprogrammer has no control on when the destructor is going to beexecuted because the garbage collector determines this. but thedestructors are called when the program exits. you can check this byredirecting the o/p of the program to a text file. i have the outputhere. notice that the destructors of the base classes are calledbecause behind the scenes base.finalize() is called.
creating a
creating b
creating c
object created
press enter to destroy it
destroying c
destroying b
destroying a
so, what do you do if you want to call the destructors once you are finished using the object? there are two ways:
call the garbage collector to clean up. implement dispose method of idisposable interface. calling the garbage collector
you can force the garbage collector to do clean up by calling the gc.collectmethod, but in most cases, this should be avoided because it may resultin performance issues. in the above program, remove the comment on gc.collect(). compile and run it. now, you can see the destructors being executed in the console itself.
implement idisposable interface.
the idisposable interface contains only one public method with signature void dispose().we can implement this method to close or release unmanaged resourcessuch as files, streams, and handles held by an instance of the classthat implements this interface. this method is used for all tasksassociated with freeing resources held by an object. when implementingthis method, objects must seek to ensure that all held resources arefreed by propagating the call through the containment hierarchy.
class myclass:idisposable
{
public void dispose()
{
//implementation
}
}
when we implement idisposable interface, we require discipline to ensure that dispose is called properly.
using the destructor and idisposable interface together
public class myclass:idisposable
{
private bool isdisposed=false;
public void dispose()
{
dispose(true);
gc.supressfinalize(this);
}
protected void dispose(bool diposing)
{
if(!isdisposed)
{
if(disposing)
{
//clean up managed resources
}
//clean up unmanaged resources
}
isdisposed=true;
}
~myclass()
{
dispose(false);
}
}
here the overload of dispose(bool)does the cleaning up, and all the cleaning up code is written only inthis method. this method is called by both the destructor and the idisposable.dispose(). we should take care that the dispose(bool) is not called from any where else except from the idisposable.dispose() and the destructor.
when a client calls idisposable.dispose(), then theclient deliberately wants to clean up the managed and unmanagedresource, and so the cleaning up is done. one thing you must havenoticed is that we called gc.supressfinalize(this)immediately after we cleaned up the resource. this method tells thegarbage collector that there is no need to call its destructor becausewe have already done the clean up.
notice that in the above example, the destructor calls the dispose with parameter as false.here, we are ensuring that the garbage collector collects the managedresources. we only do the cleaning up of unmanaged resource.
conclusion
even though we have spent some time implementing the idisposable interface, what if the client doesn’t call them properly? c# has a cool solution for this. the ‘using’ block. it looks like this:
using (myclass objcls =new myclass())
{
}
when the control exits from the using block either by running successfully and reaching the closing braces or by throwing an exception, the idispose.dispose() of myclass will be executed. remember the object you instantiate must implement the system.idisposable interface. the using statement defines a scope at the end of which an object will be disposed.
about ansil
ansilis an mcad in .net and he hails from trivandrum .he is an independentconsultant and has got software development experiences in asp.net ,mfc,visual c# ,asp , sql server2000 ,c# webservices , com+ and xml .hespends his time reading technical articles ,searching the net forlatest news about various technologies,and he plays cricket and has apassion of watching horror movies .
“first they ignore you;then they laugh at you ;then they fight you ;then you win “
click here to view ansils online profile.