HI WELCOME TO SIRIS

C# Destructor

Leave a Comment
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.

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.
  1. using System;  
  2.    public class Employee  
  3.     {  
  4.         public Employee()  
  5.         {  
  6.             Console.WriteLine("Constructor Invoked");  
  7.         }  
  8.         ~Employee()  
  9.         {  
  10.             Console.WriteLine("Destructor Invoked");  
  11.         }  
  12.     }  
  13.    class TestEmployee{  
  14.        public static void Main(string[] args)  
  15.         {  
  16.             Employee e1 = new Employee();  
  17.             Employee e2 = new Employee();  
  18.         }  
  19.     }  
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

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

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.