SyntaxStudy
Sign Up
C# Method Declarations and Overloading
C# Beginner 1 min read

Method Declarations and Overloading

Methods in C# are declared inside a type and optionally preceded by access modifiers, the `static` keyword, and a return type. A method that returns nothing uses `void`. C# supports method overloading: multiple methods with the same name but different parameter lists (differing in type, count, or order). Expression-bodied members (introduced in C# 6 and extended in later versions) allow single-expression methods to be written with `=>` instead of a full block, removing the need for `return` and curly braces. They work for methods, properties, constructors, and more. Local functions, introduced in C# 7, are methods declared inside another method. They can access the enclosing scope's variables and parameters, making them a clean alternative to private helper methods when the logic is only relevant to one caller.
Example
// Method overloading, expression-bodied members, and local functions

static class MathUtils
{
    // Method overloading — same name, different signatures
    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;

    // Full-body method
    public static double HypotenuseLength(double a, double b)
    {
        double sumSquares = (a * a) + (b * b);
        return Math.Sqrt(sumSquares);
    }

    // Generic method
    public static T Clamp<T>(T value, T min, T max) where T : IComparable<T>
    {
        if (value.CompareTo(min) < 0) return min;
        if (value.CompareTo(max) > 0) return max;
        return value;
    }
}

Console.WriteLine(MathUtils.Add(1, 2));          // 3
Console.WriteLine(MathUtils.Add(1.5, 2.5));      // 4.0
Console.WriteLine(MathUtils.Add(1, 2, 3));        // 6
Console.WriteLine(MathUtils.HypotenuseLength(3, 4)); // 5

// Local function example
static string FormatName(string first, string? middle, string last)
{
    return $"{Normalise(first)} {(middle is null ? "" : Normalise(middle) + " ")}{Normalise(last)}".Trim();

    // Local function — only visible inside FormatName
    static string Normalise(string s) =>
        string.IsNullOrWhiteSpace(s) ? "" : char.ToUpper(s[0]) + s[1..].ToLower();
}

Console.WriteLine(FormatName("alice", null, "SMITH"));    // Alice Smith
Console.WriteLine(FormatName("bob", "james", "jones"));   // Bob James Jones