CSharp - Use base to call parent instance method

Introduction

In this example, we are calling a parent class method (ParentMethod()) through the base keyword from a derived class method.

Demo

using System;

class Parent/* w ww . j  ava  2  s . c o m*/
{
    public void ParentMethod()
    {
        Console.WriteLine("I am inside the Parent method");
    }
}
class Child : Parent
{
    public void childMethod()
    {
        Console.WriteLine("I am inside the Child method");
        Console.WriteLine("I am calling the Parent method now");
        base.ParentMethod();
    }

}

class Program
{
    static void Main(string[] args)
    {
        Child obChild = new Child();
        obChild.childMethod();
    }
}

Result

Note

base keyword access is permitted only in

  • a constructor,
  • an instance method, or
  • an instance property access.

The keyword "base" should not be used in a static method context.

Related Topic