Click here to Skip to main content
13,052,163 members (52,396 online)
Click here to Skip to main content
Add your own
alternative version


75 bookmarked
Posted 23 Jul 2004

Destructors in C#

, 23 Jul 2004
Rate this:
Please Sign up or sign in to vote.
This article is about destructors in C#.


In the enterprise application development world, the buzzwords are Performance, Scalability, and Security. I started my career as a VC++ programmer, and one fine morning, I was transferred to Web development department. Like every C++ programmer, I also was frustrated. I thought every Tom, Dick, and our very own Harry can program in HTML. But, soon I found that the real challenge is to produce high performance, scalable, and reliable applications. And above all that the loosely coupled, stateless nature of web environment is always going to haunt you.

In order to produce high performance scalable applications, it is important to use your resources in an optimized manner. One tip is that use your resource as late as you can and free it at the earliest after your use. My intention here is to describe the object cleaning up mechanism used in C#.


As we all know, ‘Destructors’ are used to destruct instances of classes. When we are using destructors in C#, we have to keep in mind the 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 be executed because this is determined by the Garbage Collector. The garbage collector checks for objects that are no longer being used by the application. It considers these objects eligible for destruction and reclaims their memory. Destructors are also called when the program exits. When a destructor executes what is happening behind the scenes is that the destructor implicitly calls the Object.Finalize method on the object's base class. Therefore, the preceding destructor code is implicitly translated to:

protected override void Finalize()
      // Cleaning up .

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");
  Console.WriteLine("Destroying A");

class B:A
 public B()
  Console.WriteLine("Creating B");
  Console.WriteLine("Destroying B");

class C:B
 public C()
  Console.WriteLine("Creating 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");


As we expect, the constructors of base classes will be executed and program will wait for the user to press 'enter'. When this occurs, we set the object of class C to null. But the destructors are not executing ..!!?? As we already said, the programmer has no control on when the destructor is going to be executed because the Garbage Collector determines this. But the destructors are called when the program exits. You can check this by redirecting the o/p of the program to a text file. I have the output here. Notice that the destructors of the base classes are called because 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.Collect method, but in most cases, this should be avoided because it may result in 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 resources such as files, streams, and handles held by an instance of the class that implements this interface. This method is used for all tasks associated with freeing resources held by an object. When implementing this method, objects must seek to ensure that all held resources are freed by propagating the call through the containment hierarchy.

class MyClass:IDisposable
    public void Dispose()

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()
 protected void Dispose(bool Diposing)
   //Clean Up managed resources
  //Clean up unmanaged resources

Here the overload of Dispose(bool) does the cleaning up, and all the cleaning up code is written only in this 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 the client deliberately wants to clean up the managed and unmanaged resource, and so the cleaning up is done. One thing you must have noticed is that we called GC.SupressFinalize(this) immediately after we cleaned up the resource. This method tells the Garbage Collector that there is no need to call its destructor because we 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 managed resources. We only do the cleaning up of unmanaged resource.


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.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Software Developer (Senior)
India India
Ansil hails from Trivandrum.
He works for Microsoft india (R&D ).
he blogs at

"First they ignore you;then they laugh at you ;then they fight you ;then you win "

You may also be interested in...

Comments and Discussions

GeneralNice Pin
jakss6-Apr-15 19:40
memberjakss6-Apr-15 19:40 
GeneralMy vote of 3 Pin
ardvisoor6-Aug-13 11:49
memberardvisoor6-Aug-13 11:49 
QuestionThe Behavior of a Destructor and IDisposable Interface in C# in 2012 A.D. Pin
totallyweb7-Apr-12 10:15
membertotallyweb7-Apr-12 10:15 
GeneralThanks for Info Pin
YoUrY2-Aug-11 11:13
memberYoUrY2-Aug-11 11:13 
GeneralMy vote of 5 Pin
MannaiKarthik25-May-11 1:59
memberMannaiKarthik25-May-11 1:59 
Fantastic Ansil
GeneralMy vote of 5 Pin
papu200018-Apr-11 7:21
memberpapu200018-Apr-11 7:21 
GeneralPerfect. Pin
DontTouchBadThing28-Mar-11 16:16
memberDontTouchBadThing28-Mar-11 16:16 
GeneralMy vote of 1 Pin
Rahul Misra 20006-Feb-11 7:52
memberRahul Misra 20006-Feb-11 7:52 
GeneralRe: My vote of 1 Pin
ravistrs19-Aug-15 2:11
memberravistrs19-Aug-15 2:11 
GeneralTa bien Pin
Member 18414218-Jan-11 0:40
memberMember 18414218-Jan-11 0:40 
QuestionWhat is the sequence of methods call ?? Pin
Navin C. Pandit14-Dec-09 20:17
memberNavin C. Pandit14-Dec-09 20:17 
GeneralCongratulations Pin
Anonymous18-Jul-05 0:44
sussAnonymous18-Jul-05 0:44 
GeneralFinalizers are not Destructors Pin
Anonymous21-Apr-05 6:38
sussAnonymous21-Apr-05 6:38 
Generalsmall correction Pin
Anand Paranjpe29-Mar-05 21:50
memberAnand Paranjpe29-Mar-05 21:50 
GeneralFurther reading Pin
Ansil2-Aug-04 19:44
memberAnsil2-Aug-04 19:44 
QuestionAn Example perhaps? Pin
Mark Focas2-Aug-04 7:02
memberMark Focas2-Aug-04 7:02 
AnswerRe: An Example perhaps? Pin
Ansil2-Aug-04 19:30
memberAnsil2-Aug-04 19:30 
GeneralRe: An Example perhaps? Pin
i.i. wiin21-Jun-06 13:14
memberi.i. wiin21-Jun-06 13:14 
AnswerRe: An Example perhaps? Pin
Arch4ngel5-Aug-04 5:40
memberArch4ngel5-Aug-04 5:40 
GeneralRe: An Example perhaps? Pin
Mark Focas5-Aug-04 19:28
memberMark Focas5-Aug-04 19:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 24 Jul 2004
Article Copyright 2004 by Ansil
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid