Sunday, January 20, 2013

Call base class parameterize constructor from derive class constructor in c#?


Call base class parameterize constructor 

Base class constructor automatically call if it is not parameterize. You don’t need to write down extra code for that. But if base class construcotor is parameterize then you have to write down some code to call the base class constructor.

Syntex:

Add the below code next to the derive class constructor.

: base(parameter)

Example

   // Base Class.  
    public class Parent
    {
        string _empName = string.Empty;

        //Base class constructor.  
        public Parent(string name)
        {
            _empName = name;
        }

        public string EmpName
        {
            get
            {
                return _empName;
            }
        }
    }

    // derive Class.
    public class Child : Parent
    {
        int _empAge;

        // derive class constructor
        public Child(string name, int age)
            : base(name) //  Calling base class constructor with parameter.
        {
            _empAge = age;
        }

        public int EmpAge
        {
            get
            {
                return _empAge;
            }
        }
    }


    static void Main(string[] args)
    {
        Child objChild = new Child("Anil", 25);
        Console.WriteLine("Name - "+objChild.EmpName);
        Console.WriteLine("Age - " + objChild.EmpAge);
    }

Output

Name – Anil
Age - 25

Note: In base class and derive class, every time base class constructor first call and then derive class constructor call.

No comments:

Post a Comment