Methods, Parameters (ref/out/in) & Overloading Masterclass
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.
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)}");
| Modifier | Direction | Caller Requirement | Callee Requirement |
|---|---|---|---|
ref | Two-way (In / Out) | Must be initialized before passing | Can read & modify value |
out | One-way (Out only) | Does NOT need to be initialized before passing | MUST assign a value before returning |
in | One-way (Read-only In) | Must be initialized before passing | ReadOnly โ cannot modify value |
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}");
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.