C# Keywords Tutorial Part 62: override

C# Keywords Tutorial Part 62: override

C# is an object-oriented programming language that allows developers to create reusable code through inheritance. The “override” keyword is an important feature of C# that enables developers to change the behavior of a method in a subclass.

In this blog post, we’ll explore what the “override” keyword is, how it works, and provide some code examples to help you better understand its use.

The “override” keyword is used to indicate that a method in a subclass is intended to override a method in its parent class. This means that when the subclass method is called, it will replace the implementation of the parent method with its own implementation. This enables the subclass to customize the behavior of the parent method to suit its specific needs.

Here’s an example to illustrate this point:

class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal sound");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}

static void Main(string[] args)
{
    Animal animal = new Animal();
    Dog dog = new Dog();

    animal.MakeSound(); // Output: Animal sound
    dog.MakeSound();    // Output: Woof!
}

In this example, we have a class called Animal that defines a method called MakeSound. This method is marked as “virtual”, which means that it can be overridden by a subclass. We then have a subclass called Dog that overrides the MakeSound method with its own implementation.

When we create an instance of the Animal class and call the MakeSound method, we get the output “Animal sound”. However, when we create an instance of the Dog class and call the MakeSound method, we get the output “Woof!”. This is because the Dog class has overridden the implementation of the MakeSound method with its own implementation.

The “override” keyword is also useful when you want to add additional functionality to a method in a subclass without completely replacing its behavior. Here’s an example:

class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal sound");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
        base.MakeSound(); // Call the parent implementation
    }
}

static void Main(string[] args)
{
    Dog dog = new Dog();
    dog.MakeSound();
}

In this updated example, we have added a call to the parent implementation of the MakeSound method using the “base” keyword. This means that when we call the MakeSound method on an instance of the Dog class, we will get the output “Woof!” followed by “Animal sound”. This allows us to add additional behavior to the method while still preserving the behavior of the parent method.

Share this post

Leave a Reply

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