Destructors in C#

Itorian
Posted by in C# category on for Beginner level | Points: 250 | Views : 7321 red flag

In this quick post we will learn all about destructors and its all properties.

Before reading this post I will recommend you to read Constructors in C# post. Dot Net (.NET) framework has an in built mechanism known as Garbage Collection to deallocate memory occupied by the unused objects. In other word, destructor is something like method and constructor except that the runtime calls it after the last reference to object has disappeared. A destructor same name as the name of the class but it starts with the character ~.

An example given below has

using System;

 

class ClassRoom

{

    private int boycount;       //field

 

    public ClassRoom()          //default constructor

    {

        boycount = 30;

    }

 

    ~ ClassRoom()

    {

        boycount = 0;

    }

 

    static void Main(string[] args)

    {

        ClassRoom r;                //creating a class variable, object

        r = new ClassRoom();        //initializing class variable

                                    //or direct use "ClassRoom r = new ClassRoom();"

        int x = r.boycount;

        Console.WriteLine(x);

        Console.ReadKey();

    }

}

In above example, we have a constructor and a destructor named ClassRoom. Remember class name, constructor name and destructor names are always same in general situations, they might be different sometimes.

There are some restrictions apply to destructors:

(i) Destructors cannot be defined in struct. They are only apply to reference types. We cannot declare a destructor in a value type such as struct. For example:

struct ClassRoom

{

     ~ClassRoom() {….}    //compile-time error will appear

}

 

(ii) A class can only have one destructor. A single destructor will flush all unused memory. For example:

class ClassRoom

{

    ....

 

    ~ ClassRoom()

    {

        //place something

    }

 

    ~ClassRoom()

    {

        //place something    //compile-time error will appear

    }

 

    static void Main(string[] args)

    {

        ....

    }

}

}

(iii) Destructors cannot be inherited or overloaded.

(iv) Destructors cannot be called. They are invoked automatically.

(v) A destructor does not take modifiers or have parameters.

(vi) We cannot specify an access modifier such as public for a destructor. We cannot call destructor in our code as it is part of runtime calls from garbage collector.

(vii) C# Compiler automatically translates a destructor into an override of the Object.Finalize method. For example:

class ClassRoom

{

    ....

 

    ~ ClassRoom()

    {

        //place something

    }

 

    ....

}

into

 

class ClassRoom

{

    protected override void Finalize()

    {

        try

        {

            //place something

        }

        finally

        {

            base.Finalize();

        }

    }

}

Why my destructor codes placed in try catch block automatically?

To answer this question think, C# provided us to write our own destructors code that may be wrong or they may contain some error. So, to ensure destructor always calls its base class destructor, even if an exception occurs during your destructor code, only compiler can make this translation, we do not have freedom to write our own method to override Finalize and even we cannot call Finalize.

I hope you love this. Please post your feedbacks on this post.

HAVE A HAPPY CODING!!

Page copy protected against web site content infringement by Copyscape

About the Author

Itorian
Full Name: Abhimanyu Kumar Vatsa
Member Level: Starter
Member Status: Member
Member Since: 4/21/2011 3:54:53 AM
Country: India
Student of M.Tech IT | Microsoft MVP | Mindcracker MVP | IT Faculty | Blogger | Author
http://www.itorian.com
Abhimanyu Kumar Vatsa (Abhimanyu Kumar Singh) is a Microsoft MVP and Mindcracker (C# Corner) MVP (2010, 2011) and having experience in building web scale applications using Microsoft Technologies including ASP.NET, MVC, C#/VB, jQuery, JavaScript, Silverlight, SQL Server and many more web stuffs. He is also handy in non-Microsoft Technologies like PHP, ColdFusion etc but he's specility is always Microsoft. He love to work with Internet scale projects using Microsoft stuffs that has potential to change the every day use of technology. He love to blog and started it around June 2009 and because such blogging Microsoft awarded him MVP.

Login to vote for this post.

Comments or Responses

Posted by: Akiii on: 8/23/2011 | Points: 25
Good one itorian...

Thanks and Regards
Akiii
Posted by: Vishvvas on: 8/25/2011 | Points: 25
Good explanation. Can you throw some light on the usage scenario for destructors i.e. when and where to use? And probably also how to use? Because while employing destructor, one might need to perform GC.SupressFinalize() or so.
Thanks

Login to post response

Comment using Facebook(Author doesn't get notification)