0
0
C Sharp (C#)programming~5 mins

Base keyword behavior in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The base keyword helps you use features from a parent class inside a child class. It lets you reuse and extend code easily.

When you want to call a method from the parent class inside a child class method.
When you want to access a parent class constructor from a child class constructor.
When you want to use a property or field defined in the parent class from the child class.
When you want to override a method but still use the original behavior from the parent.
Syntax
C Sharp (C#)
class ChildClass : ParentClass
{
    public ChildClass() : base() { }

    public override void SomeMethod()
    {
        base.SomeMethod();
        // additional code
    }
}

base() calls the parent class constructor.

base.MethodName() calls a method from the parent class.

Examples
Here, base.Show() calls the Show method from the parent class inside the child class.
C Sharp (C#)
class Parent
{
    public void Show() => Console.WriteLine("Parent Show");
}

class Child : Parent
{
    public void ShowChild()
    {
        base.Show();
        Console.WriteLine("Child Show");
    }
}
The child constructor calls the parent constructor using base() before running its own code.
C Sharp (C#)
class Parent
{
    public Parent()
    {
        Console.WriteLine("Parent constructor");
    }
}

class Child : Parent
{
    public Child() : base()
    {
        Console.WriteLine("Child constructor");
    }
}
The child overrides Greet but still calls the parent's version first using base.Greet().
C Sharp (C#)
class Parent
{
    public virtual void Greet() => Console.WriteLine("Hello from Parent");
}

class Child : Parent
{
    public override void Greet()
    {
        base.Greet();
        Console.WriteLine("Hello from Child");
    }
}
Sample Program

This program shows how the base keyword calls the parent constructor and method from the child class.

C Sharp (C#)
using System;

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

    public virtual void Display()
    {
        Console.WriteLine("Display method in Parent");
    }
}

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

    public override void Display()
    {
        base.Display();
        Console.WriteLine("Display method in Child");
    }
}

class Program
{
    static void Main()
    {
        Child c = new Child();
        c.Display();
    }
}
OutputSuccess
Important Notes

You cannot use base in static methods because base refers to instance members.

If the parent class method is not marked virtual or abstract, you cannot override it but can still call it with base.

Summary

The base keyword lets child classes access parent class members.

Use base() to call the parent constructor.

Use base.Method() to call a parent method inside an overridden method.