C# Inheritance and Constructors with Programming Examples

In this chapter you will learn
  • Define Constructor in Base Class
  • Access Base Class Constructor in Derived Class
  • Programming Examples and Codes

Define Base Class Constructor

There is no special rule for defining base class constructors. Rules are same as other class constructors. You can define number of constructor as follows:

class baseclass
    {
        public baseclass()
        {
            
        }
        public baseclass(string message)
        {
            
        }
    }

 

Access Base Class Constructor in Derived Class

If base class has constructor then child class or derived class are required to call the constructor from its base class.

class childclass : baseclass
    {
        public childclass()
        {
        }
        public childclass(string message)
            : base(message)
        {            
        }
    }

Programming Examples and Codes

Following programming example has two constructors in base class. One is default constructor and other has a string parameter message. In child class all these two constructors are called and print message on console.

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

namespace Inheritance_Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            childclass ch = new childclass();
            childclass ch1 = new childclass("Hello Constructor");            
            Console.ReadKey();
        }
    }

    class baseclass
    {
        public baseclass()
        {
            Console.WriteLine("I am Default Constructors");
        }
        public baseclass(string message)
        {
            Console.WriteLine("Constructor Message : " + message);
        }
    }

    class childclass : baseclass
    {
        public childclass()
        {
        }
        public childclass(string message)
            : base(message)
        {            
        }
    }    
}

Output
I am Default Constructors
Constructor Message : Hello Constructor
_

Summary

In this chapter you learned how to define constructor in base class and call it in child class. C# Inheritance Constructor is very useful when you need to pass value to base class from child class. In the next chapter you will learn Multiple Inheritance in C#.

 

Share your thought