Sunday, September 19, 2010

Constructor and Destructor

by Emmaneale Mendu
Constructors:

Constructors are nothing but methods that are called automatically at the time of birth or creation of the object. This should have a name, same to the class name. Let see with an example.


class abc
    {
        static void Main()
        {
            xyz a = new xyz();

            Console.ReadKey();
        }
    }

    class xyz
    {
        public xyz()
        {
            Console.WriteLine("I am Constructor");
        }
    }

OutPut
I am Constructor

Above example you see class 'xyz' as a method with same name that constructor so when an object is created for 'xyz' then xyz() method called automatically. Let’s try this differently as shown below.

class abc
    {
        static void Main()
        {
            xyz a = new xyz();
            a.xyz(); //Error

            Console.ReadKey();
        }
    }

    class xyz
    {
        public xyz()
        {
            Console.WriteLine("I am Constructor");
        }
    }

Error 1 'ConsoleApplication2.xyz' does not contain a definition for 'xyz' and no extension method 'xyz' accepting a first argument of type 'ConsoleApplication2.xyz' could be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\emendu\My Documents\Visual Studio 2008\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs 13 15 ConsoleApplication2

Oops! Error, by seeing we came to know that we cannot call constructor manually. OK

Destructors:

A destructor is also a method/function with the same name as class name like constructor but basic difference is

Constructor = ‘public method_name()’
Destructor = ‘~method_name()’

Explanation wise, a constructor gets called at birth whereas a destructor gets called at death.

Move forward and check example to get brief idea.

class abc
    {
        static void Main()
        {
            xyz a = new xyz();

            Console.ReadKey();
        }
    }

    class xyz
    {
        public xyz()
        {
            Console.WriteLine("I am in Constructor");
        }

        ~xyz()
        {
            Console.WriteLine("I am in Destructor");
        }
    }

OuPut
I am in Contructor
I am in Destructor

No comments:

Post a Comment