CSharp - Use base to call parent constructor

Introduction

In C#, there is a special keyword called base.

It is used to access the members of the parent class (base class).

Whenever a child class wants to refer to its immediate parent, it can use the base keyword.

The following code shows how to use base keyword to call constructor from parent class.

Demo

using System;

class Parent//w  w w . j a  v  a  2  s  .  c  o  m
{
    private int a;
    private int b;
    public Parent(int a, int b)
    {
        Console.WriteLine("I am in Parent constructor");
        Console.WriteLine("Setting the value for instance variable a and b");
        this.a = a;
        this.b = b;
        Console.WriteLine("a={0}", this.a);
        Console.WriteLine("b={0}", this.b);
    }
}
class Child : Parent
{
    private int c;
    public Child(int a, int b, int c) : base(a, b)

    {
        Console.WriteLine("I am in Child constructor");
        Console.WriteLine("Setting the value for instance variable c");
        this.c = c;
        Console.WriteLine("c={0}", this.c);
    }

}

class Program
{
    static void Main(string[] args)
    {
        Child obChild = new Child(1, 2, 3);
        //Console.WriteLine("a in ObB2={0}", obChild.a);// a is private,
        //so Child.a is inaccessible
    }
}

Result

Analysis

In the code above, it used the base to call constructor from parent class.

In this way we can use the parent constructor to initialize private fields from parent class.

Related Topic