जगदीश खोलिया: Chain constructor or constructor chaining

Monday, June 4, 2012

Chain constructor or constructor chaining

We can chain the call of constructor from child class to base class depending on our requirement. This concept makes sure that the matching base class constructor must be called based on the parameter passed to the child class constructor.

Example:

namespace ConsoleApplication1

{

    class A

    {

        public A(){

            Console.WriteLine("Constructor A.");

        }

        public A(string s){

            Console.WriteLine("Constructor A with parameter = {0}",s);

        }

        public A(string s,string t){

            Console.WriteLine("Constructor A with parameter = {0} & {1}", s,t);

        }

    }



    class B:A

    {

        public B():base(){

            Console.WriteLine("Constructor B.");

        }

        public B(string s):base(s){

            Console.WriteLine("Constructor B with parameter = {0}", s);

        }

        public B(string s, string t):base(s,t){

            Console.WriteLine("Constructor B with parameter = {0} & {1}", s, t);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            B b1 = new B();

            B b2 = new B("First Parameter ", "Second Parameter");



            Console.Read();

        }

    }

}

Output:
Constructor A.
Constructor B.
Constructor A with parameter = First Parameter & Second Parameter
Constructor B with parameter = First Parameter & Second Parameter

No comments: