C# Destructor - How to use

In this chapter you will learn
  • What is Destructor in C#?
  • What is the use of Destructor in Program?
  • How to use it in Program?

What is Destructor (~)?

Destructors are the techniques to remove instances of classes as soon as class closed. It is very useful techniques to clean memory and remove all the instances of the program. Using of destructors you can release memory if your program is using the expensive external resource as files, image etc.

Note: You should not use empty destructor in program. When you use destructor, an entry is created in Finalize queue. Therefore, when the destructor is called, the garbage collector invoked to process the queue. If you have used empty destructor, it causes unnecessary system performance issue.

When a Destructor called it automatically invokes Finalize Method. Finalize method in C# is used for cleaning memory from unused objects and instances. So, when you call the destructor, it actually translates into following code.

 
protected override void Finalize()
{
    try
    {
        // Cleanup statements...
    }
    finally
    {
        base.Finalize();
    }
}

The programmer has no control when destructor will be executed because it is defined by garbage collector. Garbage collector automatically checks for objects that is no longer referenced or no longer being used by application. When garbage collector found such objects, it removes them automatically and free up memory.

In actually, C# doesn’t require explicit memory management because the .Net Framework garbage collector automatically does it for you.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Destructor
{
    class first
    {
        public first()
        {
            Console.WriteLine("First Object Created. Press Enter to destroy it.");
        }
        ~first()
        {
            Console.WriteLine("Destroying First Object");            
            Console.ReadLine();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            first ft = new first();
            Console.ReadLine();
        }
    }
}

Summary

In this chapter you have learned what destructor is in c # and how to use it for cleaning memory from unused objects and instances. In the next chapter you will learn about Constructor Overloading.

 

Share your thought