C Sharp Destructor | C# Destructor - c# - c# tutorial - c# net




What is destructor in C#?

  • A destructor works opposite to constructor, It destructs the objects of classes.
  • It can be defined only once in a class. Like constructors, it is invoked automatically.
  • A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object.
  • Destructors doesn't look very much like other methods in C#. ... Once the object is collected by the garbage collector, this method is called.
  • 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.
Destructor

Destructor

  • Note: C# destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.

C# Constructor and Destructor Example

  • Let's see an example of constructor and destructor in C# which is called automatically.
using System;  
   public class Employee  
    {  
        public Employee()  
        {  
            Console.WriteLine("Constructor Invoked");  
        }  
        ~Employee()  
        {  
            Console.WriteLine("Destructor Invoked");  
        }  
    }  
   class TestEmployee{  
     public static void Main(string[] args)  
        {  
            Employee e1 = new Employee();  
            Employee e2 = new Employee();  
        }  
    }  
click below button to copy the code. By - c# tutorial - team

C# examples - Output :

Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
  • Note: Destructor can't be public. We can't apply any modifier on destructors.


Related Searches to C Sharp Destructor | C# Destructor

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add wikitechy.com to your ad blocking whitelist or disable your adblocking software.

×