Sunday, January 31, 2010

.NET constructors and destructors

Explain constructor and destructor with an example using C#.NET.

A constructor is a member function that performs the task of initializing the objects with the default values to be assigned after creation.
A destructor is a function that is run to release the resources held by an object when it is no longer needed by the application.
In C#.NET we can create constructor and destructor in the following manner:
-----------------CONSTRUCTOR---------
class C
{
       private int x;    
       private int y;
       public C (int i, int j)
       {
                 x = i;
                 y = j;
       }
       public void display ()     
       {
               Console.WriteLine(x + "i+" + y);
       }
}
-----------------DESTRUCTOR---------

class D
{
        public D()
        {
            // constructor
        }         
        ~D()
        {
           // Destructor
        }
}

0 Comments: