5/20/2010

C# Destructor



Destructor
==========

Destructor is automatically invoked, when the object of the class is destroyed.

To declare destructor it must contain the same name as the class name itself but pre_fixed (~) operator.

Destructor is a complement of the constructor.

Destructor does not contain any parameter, normally it does not contain anything.

Example
-------     class person {
  string name;
  public person(){} //Constructor
  -------------
  -------------
  ~person(){}       //Destructor
     } 
  

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

namespace Destructor
{
    class sample
    {
        public int x;
        public sample(int x)
        {
            this.x = x;
            Console.WriteLine("Constructing.");
        }
        ~sample()
        {
            Console.WriteLine("Destructing!");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            sample s1 = new sample(4);
            sample s2 = new sample(8);

            Console.WriteLine("Value_1 : " + s1.x);
            Console.WriteLine("Value_2 : " + s2.x);
        }
    }
}