Using the Method Overloading and Method Overriding features in C# 13 – Reliable Hosting ASP.NET Reviews
ASP.NET Hosting

Using the Method Overloading and Method Overriding features in C# 13

Method Overloading

In programming, methods within a class might have different argument lists but the same name thanks to a technique called method overloading. This type of compile-time polymorphism determines which method to execute at compile time based on the method signature. Method overloading necessitates that the parameters of the overloaded methods be distinct types, numbers, or both. By enabling methods to accomplish the same operation with varied inputs without needing different method names, this feature improves the readability and maintainability of code.

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
The Add function is overloaded with numerous parameter configurations in the code example below, enabling the class to handle a variety of input conditions. The same method name can be used for several purposes, each with a different combination of parameter types or counts, thanks to method overloading. This guarantees that the code remains clear and simple while allowing the Add function to handle a variety of inputs, including adding integers, floating-point values, and even complicated combinations. By using method overloading, the class gains flexibility and resilience. This eliminates the need to identify each variant individually and enables a simplified interface to satisfy a range of operational requirements.

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
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 behaviours.

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"));

ASP.NET Core 8.0.11 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.