C# Method Overriding

In C# programming language, method overriding refers to the scenario where a subclass defines a method with identical name, return type, and parameters as a method existing in its superclass. This concept is employed for achieving runtime polymorphism. It allows for providing a customized implementation of a method inherited from the base class. Essentially, the base class establishes a default behavior, while the derived class can enhance or entirely alter this behavior as needed.

C# Method Overriding Example

Let's consider an example to illustrate method overriding in C#.

Example

Example

using System;



class Car

{

    public virtual void Drive()  //using base class

    {

        Console.WriteLine("Car is running");

    }

}



class SpCar : Car

{

    public override void Drive()  //Overriding Drive() method

    {

        Console.WriteLine("Sports Car runs at high speed");

    }

}



class EcCar : Car

{

    public override void Drive() // Overriding Drive() method

    {

        Console.WriteLine("Electric Car runs silently");

    }

}



class MethOverride

{

    static void Main()

    {

        Car myCar;



        myCar = new SpCar();

        myCar.Drive();   // Calls SportsCar version



        myCar = new EcCar();

        myCar.Drive();   // Calls ElectricCar version

    }

}

Output:

Output

Sports Car runs at high speed

Electric Car runs silently

Explanation:

In this instance, we've utilized a base class Car that describes a virtual function Drive, which is redefined in the derived classes like SpCar and EcCar, employing the override keyword. When the program runs, the method invocation is determined according to the concrete object type rather than the reference type. Consequently, the specific overridden function is called, leading to the display of distinct output.

Keywords for Method Overriding

If we aim to implement method overriding in C#, it is necessary to employ the virtual keyword in the base class method and the override keyword in the derived class method. In C#, there are 3 different keywords available for Method Overriding:

1) Virtual keyword

In C#, the virtual keyword is primarily utilized within a base class method to indicate that the method can be overridden in a derived class. This keyword allows modification of the base class method in the derived class.

In C#, the virtual keyword is used to allow for method overriding. By marking a method as virtual in the base class, derived classes can then override that method with their own implementation. This enables polymorphic behavior, where the same method call can produce different results based on the object it is called on. Let's consider an example to demonstrate method overriding using the virtual keyword in C#:

Example

using System;

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

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

class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow");
    }
}

class Program
{
    static void Main()
    {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        animal1.MakeSound(); // Output: Bark
        animal2.MakeSound(); // Output: Meow
    }
}

In this example, the Animal class has a virtual method MakeSound, which is then overridden in the Dog and Cat classes. When calling the MakeSound method on instances of Dog and Cat stored in Animal variables, the overridden implementations in the respective classes are executed, showcasing method overriding in action.

Let's consider an example to demonstrate method overriding in C# by utilizing the Virtual Keyword.

Example

Example

using System;

class Shape

{

    public virtual double Area()

    {

        return 0;

    }

}

class Program

{

    static void Main()

    {

        Shape shape = new Shape();

        Console.WriteLine("Area: " + shape.Area());  

    }

}

Output:

Output

Area: 0

Explanation:

In this illustration, we define a Shape class containing a virtual method Area that returns 0 to signify that a shape typically lacks an area. Within the main function, we create an instance of the Shape class and call its Area function, displaying the output as Area: 0. The utilization of the virtual keyword allows subclasses to potentially redefine this function later on.

2) Override Keyword

In C# coding, the override keyword functions as a modifier primarily employed within a method of a derived class. It serves to offer a distinct implementation of a method that has been previously defined as virtual and abstract in the parent class. This allows the derived class to enhance or adjust the functionality inherited from the parent class. At runtime, the override keyword guarantees that the appropriate method is executed according to the actual object type rather than the reference type.

In C#, method overriding occurs when a derived class provides a specific implementation for a method that is already defined in its base class. This allows the derived class to customize or extend the behavior of the base class method. To indicate that a method is being overridden, the override keyword is used in the derived class. This keyword explicitly tells the compiler that the method is intentionally replacing the base class method with a new implementation. It is important to note that the method signature in the derived class must match the method being overridden in the base class, including the return type, name, and parameters. This ensures that the method in the derived class is a valid override of the base class method.

Let's consider a scenario to demonstrate the concept of method overriding in C# by utilizing the override keyword.

Example

Example

using System;

class Shape

{

    public virtual double Area()

    {

        return 0;

    }

}

class Rectangle : Shape

{

    public double Width { get; set; }

    public double Height { get; set; }

    public override double Area()

    {

        return Width * Height;

    }

}

class Program

{

    static void Main()

    {

        Rectangle rect = new Rectangle { Width = 5, Height = 3 };

        Console.WriteLine("Rectangle Area: " + rect.Area());  

    }

}

Output:

Output

Rectangle Area: 15

Explanation:

In this instance, a Shape class is created featuring a virtual Area method that initially yields a value of 0. Subsequently, the rectangle class is derived from the Shape class and redefines the Area method to calculate the product of Width and Height. Within the main function, a rectangle object is created with a width of 5 and height of 3, resulting in an Area invocation that outputs 15.

3) Base Keyword

In C#, the base keyword is primarily used to access elements of the base class within a subclass. By employing the base keyword, we are able to invoke the base class's functions or methods from the derived class. Additionally, it is used to internally trigger the constructor of the base class when inheriting.

In this C# example, we will demonstrate method overriding by utilizing the base keyword.

Consider the following scenario:

  • We have a base class named ```

using System;

class Car

{

public virtual void Drive //using base class

{

Console.WriteLine("Car is running");

}

}

class SpCar : Car

{

public override void Drive //Overriding Drive method

{

Console.WriteLine("Sports Car runs at high speed");

}

}

class EcCar : Car

{

public override void Drive // Overriding Drive method

{

Console.WriteLine("Electric Car runs silently");

}

}

class MethOverride

{

static void Main

{

Car myCar;

myCar = new SpCar;

myCar.Drive; // Calls SportsCar version

myCar = new EcCar;

myCar.Drive; // Calls ElectricCar version

}

}

Example

Sports Car runs at high speed

Electric Car runs silently
  • We then create a derived class named ```

using System;

class Shape

{

public virtual double Area

{

return 0;

}

}

class Program

{

static void Main

{

Shape shape = new Shape;

Console.WriteLine("Area: " + shape.Area);

}

}

Example

- Inside the derived class, we override the ```
Sports Car runs at high speed

Electric Car runs silently

This allows us to extend or modify the behavior of the base class method while still being able to access the base class implementation using the base keyword.

Let's consider an instance to demonstrate the process of method overriding in C# by utilizing the base keyword.

Example

Example

using System;

class Employee

{

    public virtual void Work()

    {

        Console.WriteLine("Employee is working.");

    }

}

class Manager : Employee

{

    public override void Work()

    {

        base.Work();

        Console.WriteLine("Manager is preparing reports.");

    }

}

class Program

{

    static void Main()

    {

        Manager manager = new Manager();

        manager.Work();

    }

}

Output:

Output

Employee is working.

Manager is preparing reports.

Explanation:

In this instance, we define a class named Employee containing a virtual function Work responsible for displaying a standard work message. Subsequently, the Manager class modifies the Work function to first invoke the base Work and then add its own message related to report preparation. Within the Main method, we create an instance of the Manager class and execute the Work method, which will output both messages.

Method Overriding Example in C# using Devices

Let's consider an example to demonstrate the concept of method overriding using different tools in C#.

Example

Example

using System;

class Device

{

    public virtual void Describe()

    {

        Console.WriteLine("This is a generic device.");

    }

}

class Smartphone : Device

{

    public override void Describe()

    {

        Console.WriteLine("This is a smartphone with a touchscreen.");

    }

}

class Laptop : Device

{

    public override void Describe()

    {

        Console.WriteLine("This is a laptop with a physical keyboard.");

    }

}

class Program

{

    static void Main()

    {

        Device myDevice = new Device();

        myDevice.Describe(); 

        Device devicePhone = new Smartphone();

        devicePhone.Describe(); 

        Device deviceLaptop = new Laptop();

        deviceLaptop.Describe(); 

    }

}

Output:

Output

This is a generic device.

This is a smartphone with a touchscreen.

This is a laptop with a physical keyboard.

Explanation:

In this instance, a Device class containing a virtual Describe method is demonstrated. Subsequently, the smartphone and Laptop classes override this method using the override keyword. During runtime, the specific object type (e.g., Device, Smartphone, or Laptop) dictates the execution of the Describe method variant.

Rules for Method Overriding

There are several rules for method overriding in C#. Some of them are as follows:

  • In C# method overriding, a method, property, indexer, or event may be overridden in the derived class.
  • Static methods cannot be overridden in C#.
  • We need to utilize the virtual keyword in the methods of the base class so that the methods may be overridden.
  • We have to utilize the override keyword in the subclass to override the parent class method.
  • The base keyword enables the child class to call the parent version of the method.
  • The overridden method should have the same name, return type, and parameters as they are defined in the base class.
  • Conclusion

In summary, method overriding allows us to expand or adjust the inherited method, fostering dynamic behavior and runtime polymorphism. By utilizing Virtual and Abstract, we can guarantee the execution of the appropriate method according to the specific object type. This approach enhances code flexibility, extensibility, and usability by enabling customization of the base class method in derived classes without altering the original implementation.

C# Method Overriding FAQs

  1. Could you explain the concept of method overriding in C#?

In C# programming language, method overriding in subclass allows for customization of the base class method behavior to suit specific needs, while maintaining the identical method signature for polymorphism purposes.

  1. How does method overriding differ from method overloading?

Method overriding provides a new implementation in a subclass for an inherited method, whereas method overloading involves having multiple methods with identical names but varying parameters within the same class.

  1. Is it possible to override all methods?

Only methods that are declared as virtual, abstract, or override in the base class are eligible for being overridden. Methods that are declared as sealed, static, or private are not allowed to be overridden.

  1. Could you explain the significance of the base keyword in method overriding?

The fundamental keyword within the method of a derived class invokes the version of the method from the base class that has been overridden, enabling the derived method to extend the behavior inherited from the base class.

  1. Does method overriding pertain to runtime or compile-time polymorphism?

In C#, method overriding represents a form of runtime polymorphism since the specific method to be executed is determined during runtime based on the real object type.

Input Required

This code uses input(). Please provide values below: