Translate

Constructor Inheritance in C#

Like any other Object Oriented Programming language, C# does not allow parent constructor to be automatically inherited. It need to explicitly defined in the derived class. Below is an example to explain this -

Below is the parent class -
namespace ConstructorInh
{
    public class Fruit
    {
        private readonly string _color;
 
        public Fruit(string color)
        {
            _color = color;
 
            Console.WriteLine("I am a Fruit with Color {0}", _color);
        }
    }
}

Below is the derived class -
namespace ConstructorInh
{
    public class Apple : Fruit
    {
        public Apple(string color)
            :base (color)
        {
            Console.WriteLine("I am an Apple with Color {0}", color);
        }
    }
}
Note how we inherit the parent using the ':' operator and how we call the parent constructor using ':base' operator.

Main Program -
namespace ConstructorInh
{
    class Program
    {
        static void Main(string[] args)
        {
            var apple = new Apple("Red");
        }
    }
}

When the main program instantiates Apple, it first runs the parent constructor Fruit and then executes the child class constructor Apple.