11
Lesson 11 of 35 · OOP

Methods & Functions

Methods let you encapsulate reusable blocks of logic. This lesson covers method syntax, parameters (value, ref, out, params), return types, optional parameters, named arguments, and local functions.

Declaring and Calling Methods

A method is declared inside a class with an access modifier, return type, name, and parameter list. Use void when no value is returned. Call a method by writing its name followed by parentheses.

Basic methods Methods.cs
static void Greet(string name)
{
    Console.WriteLine($"Hello, {name}!");
}

static int Add(int a, int b)
{
    return a + b;
}

// Expression-bodied shorthand (arrow function)
static double Square(double x) => x * x;

Greet("Alice");
Console.WriteLine(Add(3, 4));    // 7
Console.WriteLine(Square(5.0));  // 25

Parameters: ref, out, in

ref passes a variable by reference (can read and write). out is like ref but the variable need not be initialised before the call—used for multiple return values. in passes by reference but disallows modification (read-only reference).

ref and out RefOut.cs
static void Swap(ref int a, ref int b)
{
    int temp = a; a = b; b = temp;
}

static bool TryDivide(int a, int b, out double result)
{
    if (b == 0) { result = 0; return false; }
    result = (double)a / b;
    return true;
}

int x = 5, y = 10;
Swap(ref x, ref y);
Console.WriteLine($"{x}, {y}"); // 10, 5

if (TryDivide(10, 3, out double r))
    Console.WriteLine($"Result: {r:F3}"); // 3.333

Optional & Named Arguments

Declare optional parameters by providing a default value. Named arguments let you pass them in any order, which improves readability for methods with many parameters.

Optional and named Optional.cs
static string FormatName(string first, string last, string title = "")
    => string.IsNullOrEmpty(title)
       ? $"{first} {last}"
       : $"{title} {first} {last}";

Console.WriteLine(FormatName("Alice", "Smith"));
Console.WriteLine(FormatName("Bob", "Jones", title: "Dr."));

params & Local Functions

params lets a method accept a variable number of arguments as an array. A local function is a method defined inside another method—useful for helpers that are only relevant in one place.

params and local functions Params.cs
static int Sum(params int[] numbers)
{
    int total = 0;
    foreach (int n in numbers) total += n;
    return total;
}
Console.WriteLine(Sum(1, 2, 3, 4, 5)); // 15

// Local function example
static double CircleArea(double radius)
{
    return Compute(radius);
    double Compute(double r) => Math.PI * r * r; // local
}
Console.WriteLine(CircleArea(5)); // 78.54