Call base class constructor and its methods from child class by using "base" keyword in C#:

 

If you want to call base class methods or if you want to pass any information from derived class or child class to base class, you can do it by using base keyword.

 

By using base keyword you can call base class methods, properties and even its constructors from derived class.

 

For example you have base class Employee with constructor and some properties as shown below.

 

class Employee

{

       public Employee()

       {

       }

 

        public int Id

        {

            get;

            set;

        }

 

        public string Name

        {

            get;

            set;

        }

 

        public Employee(int id, string name)

        {

            Id = id;

            Name = name;

        }

}

 

And create another class Manager which inherits master class Employee as shown below.

 

class Manager:Employee

{  

        public Manager(int id, string name)

        {

            Id = id;

            Name = name;

        }

}

 

This example works fine, but unnecessarily you are creating the derived class constructor even though base class has constructor with same logic. Instead of that call base class constructor from derived class constructor as shown below by using base keyword.

 

class Manager:Employee

{  

        public Manager(int id, string name)

            :base(id,name)

        {

        }

}

 

Even you can call base class methods in derived class by using base keyword as shown below.

 

For example your base class Employee has some method EmpInfo() as shown below.

 

class Employee

{

       public void EmpInfo()

       {

            Console.WriteLine("This is from base class Employee");

            Console.ReadLine();

        }

}

 

You can easily call EmpInfo() method of base class from any derived class method as shown below by using base keyword.

 

class Manager:Employee

{  

        public void ChildMethod()

        {

            base.EmpInfo();

        }

}

 

                                                                                                CSharpbaseKeywordExp.zip (23.18 kb)