Here we will explain how to use destructor in c# or what is destructor in c# or how to clean unused resources in C# by using destructor with example.



destructor works opposite to constructor in C#. The destructor in C# has the same name as class. It has the special "~" character before the Name. It can be defined only once in a class. A destructor called automatically once when an object is disposed or can be used to cleanup resources used by the object. Destructor doesn’t look very much like other methods in C#.

  • C# Constructor and Destructor Example:

Let's see an example of constructor and destructor in C# which is called automatically.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace constructor
    public class Customer
        public Customer()
            Console.WriteLine("Constructor executed");
        ~ Customer()
            Console.WriteLine("Destructor executed");
        public void Display()
            Console.WriteLine("Display method executed");
    public class Program
        public static void Main(string[] args)
            Customer customer = new Customer();
        }      }





Constructor executed

Display method executed

Destructor executed

I hope this article will help to you.

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like