Base Keyword in C# - ProgramIdea

Base keyword in C#


The base keyword is used to access member of the base class from within derived class. Using base keyword, you can call base class method that has been overridden by another method. You can specify which base class constructor should be called with derived class constructor.

Call base class method from drive class

Here ParentClass has a virtual SayHello() method. ChildClass derived from ParentClass and override base class SayHello() method. Suppose you have to call ParentClass SayHello() method from ChildClass, then you can use base keyword to call ParentClass SayHello() method from ChildClass.

// base class
public class ParentClass
{
    public virtual void SayHello()
    {
        Console.WriteLine("Hello from parent class");
    }
}

// derived class
public class ChildClass : ParentClass
{
    public override void SayHello()
    {
        // Call parent class SayHello() metho
        base.SayHello();
        Console.WriteLine("Hello from child class");
    }
}

Call base class constructor from derived class.

Here ParentClass have two constructor defined and ChildClass have also two constructor. ChildClass drive from the ParentClass. Here ChildClass constructor calling ParentClass constructor using base keyword, means when ChildClass instance will created then first call ParentClass constructor that associate with ChildClass constructor after that ChildClass constructor will fire.

// base class
public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Call parent class default constructor");
    }

    public ParentClass(int a)
    {
        Console.WriteLine("Call parent class constructor with one parameter");
    }      
}

// derived class
public class ChildClass : ParentClass
{
    // In these cases base class constructor executed first
    // after that child class constructor executed
    public ChildClass():base()
    {
        Console.WriteLine("Call child class default constructor");
    }

    public ChildClass(int b) : base(b)
    {
        Console.WriteLine("Call child class constructor with one parameter");
    }       
} 

class Program
{
    static void Main(string[] args)
    {
        ChildClass objcls = new ChildClass();
        // First call ParentClass default constructor
        // after that call ChildClass default constructor
    }
}