Method overloading lets you define multiple methods with the same name but different parameter lists — the compiler picks the right one at compile time.
public static class MathHelper
{
public static int Add(int a, int b) => a + b;
public static double Add(double a, double b) => a + b;
public static int Add(int a, int b, int c) => a + b + c;
}
Console.WriteLine(MathHelper.Add(1, 2)); // 3
Console.WriteLine(MathHelper.Add(1.5, 2.5)); // 4.0
Console.WriteLine(MathHelper.Add(1, 2, 3)); // 6
public static void Print(int value) => Console.WriteLine($"int: {value}");
public static void Print(double value) => Console.WriteLine($"double: {value}");
public static void Print(string value) => Console.WriteLine($"string: {value}");
Print(42); // int: 42
Print(3.14); // double: 3.14
Print("hello"); // string: hello
class Rectangle
{
public double Width { get; }
public double Height { get; }
public Rectangle(double side) : this(side, side) { }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public double Area() => Width * Height;
}
var square = new Rectangle(5);
var rect = new Rectangle(4, 6);
Console.WriteLine(square.Area()); // 25
Console.WriteLine(rect.Area()); // 24