Saturday, 15 November 2025

The 'base' Keyword in C#

The 'base' Keyword in C#

The base Keyword in C#

In C#, the base keyword is used to refer to the immediate parent class of the current class. It is similar to the super keyword in Java.

Main Uses of base

  1. Access parent class methods: Call a method in the base class that is overridden in the derived class.
  2. Access parent class constructors: Invoke a constructor of the base class from the derived class constructor.
  3. Access parent class properties or fields: Access members of the base class that are hidden in the derived class.

Examples

1. Calling Base Class Method

class Parent {
    public void Show() {
        Console.WriteLine("Parent Show");
    }
}

class Child : Parent {
    public new void Show() {
        Console.WriteLine("Child Show");
    }

    public void Display() {
        base.Show(); // calls Parent's Show()
    }
}
    

2. Calling Base Class Constructor

class Parent {
    public Parent() {
        Console.WriteLine("Parent Constructor");
    }
}

class Child : Parent {
    public Child() : base() {  // calls Parent constructor
        Console.WriteLine("Child Constructor");
    }
}
    

Note: Use base when you want to explicitly access members or constructors of the parent class from a derived class.

No comments:

Post a Comment