25 Feb 2024
Method overloading also known as static polymorphism, in C# refers to the ability to define multiple methods in a class with the same name but with different parameters.
In C#, method overloading enables you to provide multiple versions of a method that can accept different types of arguments or a different number of arguments. C# compiler determines which version of the method to call based on the arguments provided. This is resolved at compile time, hence the term static polymorphism or compile-time polymorphism.
Example of method overloading in C#:
using System;
public class Calculator
{
// Method to add two integers
public int Add(int a, int b)
{
return a + b;
}
// Method to add three integers
public int Add(int a, int b, int c)
{
return a + b + c;
}
// Method to add two doubles
public double Add(double a, double b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
// Invoke the Add methods with different parameters
int sum1 = calculator.Add(2, 3);
int sum2 = calculator.Add(2, 3, 4);
double sum3 = calculator.Add(2.5, 3.5);
Console.WriteLine("Sum1: " + sum1);
Console.WriteLine("Sum2: " + sum2);
Console.WriteLine("Sum3: " + sum3);
}
}
In this example, the Calculator class contains three overloaded Add methods. Each method accepts a different number or type of parameters. When you invoke the Add method, the C# compiler determines which version of the method to call based on the arguments provided. This is resolved at compile time, hence the term "static polymorphism" or "compile-time polymorphism."