Wednesday, May 23, 2012

Destructors

Destructors are use to clear the memory space used by the class
It is denoted by using~  to the constructors

The program to understand a destructor is as follows

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

namespace destructors
{
    class calculator//constructor
    {
        int i, j,k;
        calculator()
        {
            i = 25;
            j = 78;
            Console.WriteLine("The Values that are initialized by the are {0},{1}",i,j);
        }
        ~calculator()//destructor
        {
            Console.WriteLine("The Values are removed");
        }
        void addnumber()
        {
            k = i + j;
            Console.WriteLine("The added value is {0}",k );
        }
        void display()
        {
            Console.WriteLine("The Value of i and j is {0},{1}",i,j);
        }
        static void Main(string[] args)
        {
            calculator d1= new calculator();//the constuctor is called
            d1.addnumber();//the function is called but at the same time the destructor will also be called
            d1.display();
            Console.ReadLine();
        }
    }
}
P.S: The Values are cleared only after we exit after runtime so we cannot see the out put in visual studio.So u can use visual stydio command prompt

No comments:

Post a Comment