Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » C# Language » Understanding Destructors in C#

Understanding Destructors in C#

This article is about understanding the working concept of destructor in C#. As you read this article you will understand how different is C# destructor are when compared to C++ destructors.

Page Views : 13003
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction 

This article is about understanding the working concept of destructor in C#. I know you all may be thinking why a dedicated article on simple destructor phenomenon. As you read this article you will understand how different is C# destructor are when compared to C++ destructors. 

In simple terms a destructor is a member that implements the actions required to destruct an instance of a class. The destructors enable the runtime system, to recover the heap space, to terminate file I/O that is associated with the removed class instance, or to perform both operations. For better understanding purpose I will compare C++ destructors with C# destructors. 

Generally in C++ the destructor is called when objects gets destroyed. And one can explicitly call the destructors in C++. And also the objects are destroyed in reverse order that they are created in. So in C++ you have control over the destructors. 

One may be thinking how C# treats the destructor. In C# you can never call them, the reason is one cannot destroy an object. So who has the control over the destructor (in C#)? it's the .Net frameworks Garbage Collector (GC). 

Now few questions arise why GC should control destructors why not us? 

The answer is very simple GC can do better object release than we can. If we do manual memory management one has to take care both allocation and de-allocation of memory. So there is always chance that one can forgot de-allocation. And also manual memory management is time consuming and complex process. So lets understand why C# forbids you from explicitly writing code for destructors. 

1. If we are accessing unmanaged code usually we forget to destroy an object. This avoids the destructor call and memory occupied by the object will never get released. 

Let examine this case by taking example, Below figure shows that Memory stacks in which application XYZ loads an unmanaged code of 30 bytes.

When applications XYZ ends imagine it forgot to do destroy an object in Unmanaged code so what happens is Application XYZ memory gets deallocated back to the heap but unmanaged code remains in memory. So Memory gets wasted.            

2. If we are trying to release the object while object is still doing some process or i mean object is still active.

3. If we are trying to release the object that is already been released. 

So lets see how GC will handle above situations: 

1. If program ends GC automatically reclaims all the memory occupied by the objects in the program.

2. GC keeps tracks of all the objects and ensures that each object gets destroyed once.

3. GC ensures that objects, which are being referenced, are not destroyed.

4. GC destroys the objects only when necessary. Some situations of necessity are memory is exhausted or user explicitly calls System.GC.Collect() method. 

Understanding the complete working of Garbage collector (GC) is a big topic. But I will cover the some its details with respect to our topic. GC is a .net framework thread, which runs when needed or when other threads are in suspended mode. So first GC creates the list of all the objects created in the program by traversing the reference fields inside the objects. This list helps the GC to know how many objects it needs to keep track. Then it ensures that there are no circular references inside this list. In this list GC then checks for all the objects, which have destructor, declared and place them in another list called Finalization List. 

So now GC creates two threads one, which are reachable list and another unreachable, or finalization List. Reachable objects are cleared one by one from the list and memory occupied by these objects are reclaimed back. The 2nd thread, which reads the finalization lists and calls, the each object finalized in separate object. 

Lets see how C# compiler understands the destructor code. Below is a small class created in visual studio .Net, I have created a class called class1 which has a constructor and a destructor.  

using System;
namespace ConsoleApplication3
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
public Class1()
{}
~Class1()
{}
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Class1 c= new Class1();
}
}
}

So after compiling the code open the assemblies in ILDASM.EXE (Microsoft Diassembler Tool) tool and see the IL code. You will see something-unusual code. In above code the compiler automatically translates a destructor into an override of the Object.Finalize() method. In other words, the compiler translates the following destructor: 

class Class1
{
~Class1(){}
}

Into following: 

In Source Code Format: In IL Code Format:

class Class1
{
Protected override void Finalize()
{
try{..}
finally { base.Finalize();}
}
}

.method family hidebysig virtual instance void
Finalize() cil managed
{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: leave.s IL_0009
} // end .try
finally
{
IL_0002: ldarg.0
IL_0003: call instance void [mscorlib]System.Object::Finalize()
IL_0008: endfinally
} // end handler
IL_0009: ret
} // end of method Class1::Finalize


The compiler-generated Finalize method contains the destructor body inside try block, followed by a finally block that calls the base class Finalize. This ensures that destructors always call its base class destructor. So our conclusion from this is Finalize is another name for destructors in C#. 

Points to remember:

1. Destructors are invoked automatically, and cannot be invoked explicitly.
2. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
3. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
4. Destructors cannot be used with structs. They are only used with classes.
5. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
6. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
7. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived. 

Further reading

1. .Net  More information on .Net technologies

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Chandra Hundigam
Chandra Hundigam has Master degree in Computer Application, Microsoft Certified Professional and Software Consultant. He's significantly involved in enterprise application development and distributed object oriented system development using Microsoft .Net, Sun Java/J2EE technology to serve global giants in the Media, finance, mortgage and software industries.Presently working as Software Consultant for a US-based company.His areas of interests are in emerging Technologies.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Thanks! by Craig On February 11, 2007
Great short and sweet explanation for someone learning C# but thinks like C++. Thanks for you time!
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.