Friday 27 May 2016

destructor

destructor

Destructor is same name as class name but starting with character ~ (tilde). Destructor has not any modifier.
A destructor is called when it’s time to destroy the object.
Simple terms, it is used to release the resource of the class object. It called when an object is being destroyed.
Destructors cannot take parameters. Destructor declare using tilde (~) prefix
Types:
All local types used in class.

Syntax:

~myClass()
{
     Console.WriteLine("Destroyed...");
}

How to define in program?

using System;

class Program
{
   
    static void Main()
    {
        //instance of class is created here
        myClass cls = new myClass();
    }
}

class myClass
{
    public myClass()
    {
        Console.WriteLine("Default instantiate...\n");
    }
    ~myClass()
    {
        Console.WriteLine("Destroyed...");
    }

}
Output:
Default instantiate…
Destroyed…
Press any key to continue…

you can also visit:  www.mybook-lang.com

No comments:

Post a Comment