Methods, Parameters (ref/out/in) & Overloading Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 14 of 35 ๐Ÿ“‚ Phase 6: Methods & OOP ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Method Signatures ยท Method Overloading ยท ref Modifier ยท out Modifier ยท in Modifier ยท Expression-Bodied Methods (=>) ยท Local Functions ยท Static Methods

Welcome to Phase 6 (Chapter 14): C# Methods, Parameter Modifiers (ref, out, in), Overloading & Expression-Bodied Members Masterclass! Methods are reusable blocks of code that perform actions. In this chapter, we explore method signatures, default parameters, named arguments, method overloading, pass-by-reference modifiers (ref, out, in), expression-bodied methods (=>), local functions, static methods, and recursion.

1Method Declaration & Method Overloading
C# โ€” Method Declaration & Overloading โ–ถ Run in Compiler
class Calculator
{
    // Standard method
    public static int Add(int first, int second)
    {
        return first + second;
    }

    // Method Overloading (same name, different parameter types)
    public static double Add(double first, double second)
    {
        return first + second;
    }

    // Expression-bodied method (C# 6+)
    public static int Multiply(int a, int b) => a * b;
}

Console.WriteLine($"Add ints: {Calculator.Add(10, 20)}");
Console.WriteLine($"Add doubles: {Calculator.Add(5.5, 4.5)}");
Console.WriteLine($"Multiply: {Calculator.Multiply(4, 5)}");
2Parameter Modifiers โ€” ref, out, and in
ModifierDirectionCaller RequirementCallee Requirement
refTwo-way (In / Out)Must be initialized before passingCan read & modify value
outOne-way (Out only)Does NOT need to be initialized before passingMUST assign a value before returning
inOne-way (Read-only In)Must be initialized before passingReadOnly โ€” cannot modify value
C# โ€” ref, out, and in Demonstration โ–ถ Run in Compiler
static void Swap(ref int x, ref int y)
{
    int temp = x; x = y; y = temp;
}

static void GetValues(out int id, out string name)
{
    id = 101;
    name = "Ravi";
}

int a = 10, b = 20;
Swap(ref a, ref b);
Console.WriteLine($"Swapped: a={a}, b={b}"); // a=20, b=10

GetValues(out int newId, out string newName);
Console.WriteLine($"Out values: ID={newId}, Name={newName}");
3Technical FAQs

Q1: What is the main difference between ref and out?

A ref parameter requires the caller to initialize the variable before calling the method. An out parameter does not require caller initialization, but the called method is forced by the compiler to assign it a value before returning.

Q2: What are Expression-Bodied Methods?

Expression-bodied methods use the lambda arrow => to define single-line methods concisely without needing braces or explicit return keywords.