6. Methods

A method is a named block of code that can take parameters and return a value. Declare it with an optional access modifier, a return type, a name and a parameter list: static int Add(int a, int b). Use void when nothing is returned. Parameters are the names in the declaration; arguments are the values you pass when you call it. Methods remove repetition, give code a meaningful name and let you test one piece at a time. A static method belongs to the type and is called as Type.Method(); an instance method belongs to an object.

By default arguments are passed by value: the method gets a copy, so changing it does not change the caller's variable (for reference types the copy is of the reference, so the method can change the object's contents). ref passes the variable itself, out lets a method hand back extra values (the variable must be assigned inside the method), and in passes a large value by read-only reference. Methods can have optional parameters with default values, named arguments, a variable number of arguments (params) and can be overloaded (same name, different parameters).

Expression-bodied methods use => for one-line methods, local functions are methods declared inside other methods, tuples let a method return several values, and a method that calls itself is recursive (it needs a base case to stop). A method that returns a value must return on every path.

Key points to remember

  • Overloads must differ in the number, types or order of parameters, not just in the return type. Overloading works for methods inside a class; local functions in a top-level program cannot be overloaded.
  • Optional parameters must come after the required ones and the default must be a compile-time constant.
  • A method should do one job and have a name that says what it does: CalculateTax, IsValidEmail, GetCustomers.
  • params must be the last parameter and there can be only one. It lets callers pass values separated by commas or an array.
  • Recursion needs a base case. Every recursive call must move closer to it or the program ends with a StackOverflowException.
  • Variables declared inside a method are local to it and disappear when it ends; share data using parameters and return values, not global variables.
  • Common mistake: expecting a method to change an int argument. Use ref/out or return the new value.
  • Async methods (covered later) return Task or Task<T> and their names end with Async.

Example 1: Parameters and return values

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

static string Greet(string name, string greeting = "Hello")
    => $"{greeting}, {name}";

Console.WriteLine(Add(2, 3));
Console.WriteLine(Greet("Ana"));
Console.WriteLine(Greet("Ana", greeting: "Hi"));
Show output Output
5
Hello, Ana
Hi, Ana

Example 2: void methods and optional / named arguments

C#
static void Print(string text, int times = 1, bool upper = false)
{
    if (upper) text = text.ToUpper();
    for (int i = 0; i < times; i++)
        Console.WriteLine(text);
}

Print("hi");
Print("hi", times: 2);
Print("hey", upper: true);
Show output Output
hi
hi
hi
HEY

Example 3: Method overloading

C#
Console.WriteLine(Calc.Add(2, 3));          // int version
Console.WriteLine(Calc.Add(2.5, 1.5));      // double version
Console.WriteLine(Calc.Add(1, 2, 3));       // three-parameter version

static class Calc
{
    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;
}
Show output Output
5
4
6

Example 4: params: a variable number of arguments

C#
static int Sum(params int[] numbers)
{
    int total = 0;
    foreach (int n in numbers) total += n;
    return total;
}

Console.WriteLine(Sum(1, 2, 3));
Console.WriteLine(Sum());
Console.WriteLine(Sum(new[] { 4, 5 }));
Show output Output
6
0
9

Example 5: Pass by value, ref and arrays

C#
static void AddOne(int x) { x++; }
static void AddOneRef(ref int x) { x++; }
static void ChangeFirst(int[] arr) { arr[0] = 99; }

int n = 5;
AddOne(n);
Console.WriteLine(n);       // unchanged: a copy was changed
AddOneRef(ref n);
Console.WriteLine(n);       // changed: the variable itself was passed

int[] data = { 1, 2, 3 };
ChangeFirst(data);          // the array object is shared
Console.WriteLine(data[0]);
Show output Output
5
6
99

Example 6: ref and out parameters

C#
static void Split(int total, out int half, out int rest)
{
    half = total / 2;
    rest = total % 2;
}

Split(9, out int h, out int r);
Console.WriteLine(h + " and " + r);

static void Swap(ref int a, ref int b) { int t = a; a = b; b = t; }
int x = 1, y = 2;
Swap(ref x, ref y);
Console.WriteLine($"{x} {y}");
Show output Output
4 and 1
2 1

Example 7: Returning several values with a tuple

C#
static (int Min, int Max, double Average) Stats(int[] numbers)
    => (numbers.Min(), numbers.Max(), numbers.Average());

var result = Stats(new[] { 4, 9, 1, 6 });
Console.WriteLine($"{result.Min} {result.Max} {result.Average}");

var (min, max, _) = Stats(new[] { 7, 3 });   // deconstruct, ignore the third
Console.WriteLine(min + " to " + max);
Show output Output
1 9 5
3 to 7

Example 8: Recursion

C#
static long Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1);

static int Fibonacci(int n)
{
    if (n < 2) return n;                        // base case
    return Fibonacci(n - 1) + Fibonacci(n - 2);
}

Console.WriteLine(Factorial(5));
Console.WriteLine(Fibonacci(7));
Show output Output
120
13

Example 9: Local functions and TryParse-style methods

C#
static int CountEvens(int[] numbers)
{
    bool IsEven(int n) => n % 2 == 0;       // local function
    int count = 0;
    foreach (int n in numbers)
        if (IsEven(n)) count++;
    return count;
}

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

Console.WriteLine(CountEvens(new[] { 1, 2, 3, 4 }));
if (TryDivide(7, 2, out double q)) Console.WriteLine(q);
Console.WriteLine(TryDivide(1, 0, out _));
Show output Output
2
3.5
False

Example 10: Static vs instance methods

C#
Console.WriteLine(MathTools.Double(21));        // called on the type

var counter = new Counter();                    // called on an object
counter.Increase();
counter.Increase();
Console.WriteLine(counter.Value);

static class MathTools
{
    public static int Double(int x) => x * 2;
}
class Counter
{
    public int Value { get; private set; }
    public void Increase() => Value++;
}
Show output Output
42
2