Thursday 19 July 2012

CONSTRUCTOR


A special method of the class that will be automatically invoked when an instance of the class is created is called as constructor.

Constructors can be classified into 5 types

·       Default Constructor
·       Parameterized Constructor
·       Copy Constructor
·       Static Constructor
·       Private Constructor

Example program using Constructors

using System;

class ProgramCall
{
    int i, j;


    //default contructor
    public ProgramCall()
    {
        i = 45;
        j = 76;
    }

    public static void Main()
    {

        //When an object is created , contructor is called
        ProgramCall obj = new ProgramCall();

        Console.WriteLine(obj.i);
        Console.WriteLine(obj.j);

        Console.Read();


    }
    }

OUTPUT

45
76

Two types constructors they are:
·       Static constructor
·       Instance constructor



Static constructor

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Example

In this example, the class Bus has a static constructor and one static member, Drive(). When Drive() is called, the static constructor is invoked to initialize the class.



public class Bus
{
    // Static constructor:
    static Bus()
    {
        System.Console.WriteLine("The static constructor invoked.");
    }

    public static void Drive()
    {
        System.Console.WriteLine("The Drive method invoked.");
    }
}
 
class TestBus
{
    static void Main()
    {
        Bus.Drive();
    }
}


Output

The static constructor invoked.

The Drive method invoked.

Instance constructor
Instance constructors are used to create and initialize instances. The class constructor is invoked when you create a new object, for example:

Example
The following example demonstrates a class with two class constructors, one without arguments and one with two arguments.

class CoOrds
{
public int x, y;

// Default constructor:
public CoOrds()
{
x = 0;
y = 0;
}

// A constructor with two arguments:
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}

// Override the ToString method:
public override string ToString()
{
return (System.String.Format("({0},{1})", x, y));
}
}

class MainClass
{
static void Main()
{
CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);

// Display the results using the overriden ToString method:
System.Console.WriteLine("CoOrds #1 at {0}", p1);
System.Console.WriteLine("CoOrds #2 at {0}", p2);
}
}


Output

CoOrds #1 at (0,0)

CoOrds #2 at (5,3)

No comments:

Post a Comment