Tuesday, September 28, 2010

Constructors


What is constructor?
  • Constructor is used to initialize an object (instance) of a class.
  • Constructor is a like a method without any return type.
  • Constructor has same name as class name.
  • Constructor follows the access scope (Can be private, protected, public, Internal and external).
  • Constructor can be overloaded.
Constructors generally following types :
  • Default Constructor
  • Parameterized constructor
  • Private Constructor
  • Static Constructor
  • Copy Constructor
The constructor goes out of scope after initializing objects.

Default Constructor

A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.
Parameterized constructor

Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.

Private Constructor

Private constructors are used to restrict the instantiation of object using 'new' operator.  A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
This type of constructors is mainly used for creating singleton object.
If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private.
We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.



Static Constructors

C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster.
Static constructors are used to initializing class static data members.
Point to be remembered while creating static constructor:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.

Copy Constructor

              If you create a new object and want to copy the values from an existing object, you use copy constructor. This constructor takes a single argument: a reference to the object to be copied.

 Consructor demo:

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

namespace Csharp
{
    ///




    /// (a)Default Constructor
    /// (b)Parameterized Constructor
    /// (c)static Constructor
    /// (d)Copy Constructor
    /// (e)Private Constructor
    ///

    class Constructor
    {
        public static void Main(string[] args)
        {

            defaultconstructor obj1 = new defaultconstructor();
            obj1.member();
            int a, b;
            Console.WriteLine("Enter the values of a,b");
            a = Convert.ToInt32(Console.ReadLine());
            b = Convert.ToInt32(Console.ReadLine());
            constructor obj = new constructor(a, b);
            obj.display();
            privateconstructor obj2 = privateconstructor.createinstance();
            obj2.result();
            staticconstructor obj3 = new staticconstructor();
            obj3.display();
            copyconstructor ob1 = new copyconstructor(10, 20);
            ob1.display();
            // Here we are using copy constructor. Copy constructor is using the values already defined with ob1
            copyconstructor ob2 =new copyconstructor(ob1);
            ob2.display();
            Console.ReadLine();
          
        }

    }
    //(a) default constructor
    class defaultconstructor
    {
        int a, b;
        public defaultconstructor()
        {
            a = 5;
            b = 6;
        }
        public void member()
        {
            Console.WriteLine("Example of defaultconstructor");
            Console.WriteLine("The values of a is: {0} \n The value of b is: {1}", a, b);
            Console.WriteLine("===========================================================");
        }
    }
    //(b)parameterized constructor
    class constructor
    {
        int a, b;
        public constructor(int x, int y)
        {
            a = x;
            b = y;
        }
        public void display()
        {
            Console.WriteLine("Example of parameterizedconstructor");
            Console.WriteLine("Value of a: {0}",a);
            Console.WriteLine("Value of b: {0}",b);
            Console.WriteLine("===========================================================");
        }
    }
    //(c) private constructor
    class privateconstructor
    {
        public int a, b; public static int c, d;
        private privateconstructor(int x, int y)
        {
            this.a=x;
            this.b = y;
        }
        public static privateconstructor createinstance()
        {
            Console.WriteLine("Enter the values");
            c = Convert.ToInt32(Console.ReadLine());
            d = Convert.ToInt32(Console.ReadLine());
            return new privateconstructor(c,d);
        }
        public void result()
        {
            int z;
            z = a + b;
            Console.WriteLine("Example of privateconstructor");
            Console.WriteLine("The result is {0}", z);
            Console.WriteLine("===========================================================");
        }
    }
    //(d) static constructor
    class staticconstructor
    {
        static string carname, carmodel;
        static staticconstructor()
        {
            carname = "BMW";
            carmodel = "BMWZ8";
        }
        public void display()
        {
            Console.WriteLine("Example of static constructor");
            Console.WriteLine("The carname is {0}\n The carmodel is {1}", carname, carmodel);
            Console.WriteLine("===========================================================");
        }
    }
    //(e) copy constructor
    class copyconstructor
    {
        int a, b;

        public copyconstructor(int x, int y)
        {
            this.a = x;
            this.b = y;
        }
        public copyconstructor(copyconstructor a)
        {
            this.a = a.a;
            this.b = a.b;
        }
        public void display()
        {
            Console.WriteLine("Example of copy constructor");
            int z = a + b;
            Console.WriteLine(z);
            Console.WriteLine("===========================================================");
        }
    }

}

No comments:

Post a Comment