Using C# 13's Method Overloading and Method Overriding

Overview

In this article, Ziggy Rafiq provides code examples for method overloading and overriding in C# 13 in order to achieve polymorphism in object-oriented programming (OOP). Even though both involve the definition of multiple methods with similar names, they serve different purposes and are implemented differently.

Method Overloading in C#

In programming, method overloading allows methods within a class to have the same name but differ in their parameter lists. Based on the method signature, the decision on which method to execute is made at compile time, which is a form of compile-time polymorphism. Method overloading requires the overloaded methods to have different parameter types, numbers, or both as their parameters. This feature enhances code readability and maintainability by allowing methods to perform the same task with different inputs without requiring different method names.

Definition

A compile-time polymorphism feature called method overloading allows multiple methods in a class with the same name but differing parameter lists.

Key Points

  • overloaded Methods must have different parameter types, numbers, or both.
  • A return type alone does not distinguish overloaded methods from non-overloaded methods.

Code Example of Method Overloading

In the code example below, we observe that the Add method is overloaded with multiple parameter configurations, allowing the class to handle a wide range of input scenarios. Using method overloading, the same method name can be used for multiple purposes, each with a different combination of parameter types or counts. This ensures that the Add method can seamlessly accommodate different inputs, such as adding integers, floating-point numbers, or even complex combinations, while maintaining clarity and simplicity in the code. The class becomes more flexible and robust by leveraging method overloading. This allows a streamlined interface to meet diverse operational needs without having to name each variation separately.


namespace MethodOverloadingOverriding.OverloadingDemo;

public class Calculator
{    
    public int Add(int a, int b)=>  a + b;
       
    public int Add(int a, int b, int c)=> a + b + c;

    public double Add(double a, double b) => a + b;

}
Console.WriteLine("***********************METHOD OVERLOADING DEMO********************************");
Calculator calculator = new Calculator();
Console.WriteLine("Adding two integers: " + calculator.Add(70, 50));
Console.WriteLine("Adding three integers: " + calculator.Add(10, 18, 65));
Console.WriteLine("Adding two doubles: " + calculator. Add(12.9, 80.3));

Method Overriding in C#

Object-oriented programming uses method overriding as a way of providing a specific implementation for a method already defined in its base class. Runtime polymorphism uses this feature to enable dynamic method dispatch, which determines the method to be executed based on the type of the object at runtime. During method overriding, the base class method must be marked with the virtual keyword so that it can be overridden in derived classes, ensuring clarity and ensuring that the overriding behaviour is intentional. The override keyword must be explicitly used in the derived class method intended to override the base class method. Additionally, the method signature of the derived class must be the same as the method signature of the base class. By adhering to these rules, method overriding facilitates a more flexible and extensible code structure, allowing subclasses to redefine or enhance inherited methods.

Definition

Using method overriding, a subclass can provide a specific implementation for a method that has already been defined in its base class. This is called runtime polymorphism.

Key Points

  • For a method to be virtual, it must be marked with the virtual keyword.
  • The override keyword must be used in the derived class method.
  • The signature of the method in the derived class must match the signature of the method in the base class.

Code Example of Method Overriding

In this code example below, the Speak method is overridden in the Dog and Cat classes to provide specific behaviors tailored to these subclasses while adhering to the same interface defined in the base class. By overriding a common method signature defined in a base class, derived classes can implement it differently. Dog and Cat classes can display their unique ways of "speaking" by overriding the Speak method, which does not change the underlying structure of the base class. In object-oriented programming, polymorphism demonstrates its versatility and practicality by ensuring consistency in method usage while allowing for diverse behaviors.

namespace MethodOverloadingOverriding.OverridingDemo;
public class Animal
{

    public virtual void Speak() =>
        Console.WriteLine("The animal makes a sound.");
    
}
namespace MethodOverloadingOverriding.OverridingDemo;
public class Cat : Animal
{   
    public override void Speak() => Console.WriteLine("The cat meows.");
    
}
namespace MethodOverloadingOverriding.OverridingDemo;
public class Dog : Animal
{
    
    public override void Speak() =>
        Console.WriteLine("The dog barks.");    
}
Console.WriteLine("***********************METHOD OVERRIDING DEMO********************************");
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

myAnimal.Speak();
myDog.Speak(); 
myCat.Speak();

Method Overloading vs. Method Overriding
 

Feature Method Overloading Method Overriding
Purpose Polymorphism is achieved at compile time. Runtime polymorphism is achieved.
Definition The name of the method is the same, but the parameters are different. The method name and parameters are the same in the subclass, but they are redefined.
Keywords It is not necessary to use special keywords. In subclasses, virtual is used in the base class and overridden in the subclass.
Scope It is the same class that contains methods. It is the responsibility of base and derived classes to implement methods.
Binding Binding at compile time. Binding at Runtime.

C# 13 Method Overloading and Overriding New Features

In C# 13, enhanced features such as pattern matching and enhanced method signatures provide more flexibility in crafting expressive and maintainable code despite not directly altering the rules for method overloading and overriding.

Code Example with Pattern Matching for Overloading

namespace MethodOverloadingOverriding.PatternMatchingOverloading;
public class Shape
{
    public string Describe(object shape)
    {
        return shape switch
        {
            Circle c => $"A circle with radius {c.Radius}",
            Rectangle r => $"A rectangle with width {r.Width} and height {r.Height}",
            _ => "Unknown shape"
        };
    }

}
namespace MethodOverloadingOverriding.PatternMatchingOverloading;

public class Circle
{
    public double Radius { get; set; }
}
namespace MethodOverloadingOverriding.PatternMatchingOverloading;
public class Rectangle
{
    public double Width { get; set; }
    public double Height { get; set; }

}
namespace MethodOverloadingOverriding.PatternMatchingOverloading;
public class Shape
{
    public string Describe(object shape)
    {
        return shape switch
        {
            Circle c => $"A circle with radius {c.Radius}",
            Rectangle r => $"A rectangle with width {r.Width} and height {r.Height}",
            _ => "Unknown shape"
        };
    }

}
Console.WriteLine("***********************PATTERN MATCHING OVERLOADING DEMO********************************");
Shape shape = new Shape();

Console.WriteLine(shape.Describe(new Circle { Radius = 5 }));
Console.WriteLine(shape.Describe(new Rectangle { Width = 10, Height = 20 }));
Console.WriteLine(shape.Describe("Unknown"));

Summary

Overriding and overloading are essential for C# code to be flexible and reusable. Overriding provides multiple ways to use a method, improving usability. Method overriding enables dynamic behaviour in derived classes, encouraging polymorphism. With C# 13's modern features, these concepts integrate seamlessly into the language's evolving landscape, making them more versatile and maintainable.


Similar Articles
Capgemini
Capgemini is a global leader in consulting, technology services, and digital transformation.