C# Keywords Tutorial Part 7: base

C# Keywords Tutorial Part 7: base

C# is a popular programming language that is widely used for building Windows applications, web applications, games, and much more. One of the essential features of C# is the base keyword. In this blog post, we will explore the base keyword in C# and its usage with code examples.

What is the base keyword in C#?

The base keyword in C# is used to access the members of a base class from within a derived class. It is used when we want to call a method, property, or field of a base class from a derived class. In simple terms, it refers to the parent class of the current class.

Usage of the base keyword in C#

  1. Accessing base class constructors

The base keyword can be used to access the constructors of the base class. When a derived class is created, its constructor must first call the constructor of its base class using the base keyword.

public class BaseClass
{
    public BaseClass(int x)
    {
        Console.WriteLine("Base class constructor called with parameter: " + x);
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass(int y) : base(y)
    {
        Console.WriteLine("Derived class constructor called with parameter: " + y);
    }
}

class Program
{
    static void Main(string[] args)
    {
        DerivedClass obj = new DerivedClass(10);
        Console.ReadLine();
    }
}

In the above example, the derived class constructor calls the base class constructor using the base keyword.

  1. Accessing base class members

The base keyword can also be used to access the members of the base class. Suppose the base class has a method, property, or field that is overridden in the derived class. In that case, we can use the base keyword to access the original implementation of the method, property, or field.

public class BaseClass
{
    public virtual void Display()
    {
        Console.WriteLine("This is the base class implementation of Display() method.");
    }
}

public class DerivedClass : BaseClass
{
    public override void Display()
    {
        base.Display(); // Accessing base class method using the base keyword
        Console.WriteLine("This is the derived class implementation of Display() method.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        DerivedClass obj = new DerivedClass();
        obj.Display();
        Console.ReadLine();
    }
}

In the above example, the derived class overrides the Display() method of the base class. However, it uses the base keyword to access the original implementation of the method before adding its implementation.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *