Methods in C#: parameters, return values, ref, out and recursion

Lesson 6 of 15 · C#

A method is a named part of a program that performs one task. Methods make a program shorter, prevent repeated code and make it easier to find errors. Here we look at static methods, which are called without an object; methods of objects come in the lesson about classes.

Before you start: required prior knowledge – arrays and strings.
How to learn: type in and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are C# console applications (.NET 8 or later, without "top-level statements"); every one has been tested and gives the output shown.

Defining and calling a method

A method has a header (modifiers, return type, name, parameters) and a body in curly brackets. The return statement returns the result and ends the method. Method names are written with a capital first letter.

using System;

class Program
{
    // static: the method belongs to the class and is called without an object
    // int: the return type; (int x): a parameter
    static int Square(int x)
    {
        return x * x;
    }

    // void: the method returns nothing, it just does something
    static void Line(int length, char symbol)
    {
        Console.WriteLine(new string(symbol, length));
    }

    static void Main()
    {
        Line(20, '=');
        for (int i = 1; i <= 4; i++)
            Console.WriteLine($"{i} squared is {Square(i)}");
        Line(20, '-');
        Console.WriteLine($"3^2 + 4^2 = {Square(3) + Square(4)}");
    }
}

When the method is called, the arguments (the actual values) are assigned to the parameters in order: in the call Line(20, '=') the parameter length gets 20, and symbol gets '='.

using System;

class Program
{
    static bool IsPrime(int n)
    {
        if (n < 2) return false;
        for (int d = 2; d * d <= n; d++)
            if (n % d == 0) return false;   // return ends the method immediately
        return true;
    }

    static int DigitSum(int n)
    {
        int s = 0;
        while (n > 0)
        {
            s += n % 10;
            n /= 10;
        }
        return s;
    }

    static int Larger(int a, int b) => a > b ? a : b;   // a one-line method (=>)

    static void Main()
    {
        string[] parts = Console.ReadLine().Split(' ');
        int a = int.Parse(parts[0]), b = int.Parse(parts[1]);
        // primes in the interval whose digit sum is also prime
        for (int x = a; x <= b; x++)
            if (IsPrime(x) && IsPrime(DigitSum(x)))
                Console.Write(x + " ");
        Console.WriteLine();
        Console.WriteLine($"The larger of {a} and {b} is {Larger(a, b)}");
    }
}

A method that returns bool makes a condition readable: if (IsPrime(n)) reads like a sentence. A short method can be written on one line, after the => sign.

Passing arguments: by value, ref and out

By default a method gets a copy of the argument's value, so changing the parameter does not affect the variable in the call. With ref the method works with the variable itself, and out lets a method return several results. The word ref or out is also written in the call.

using System;

class Program
{
    static void Increase(int x)
    {
        x += 10;                        // only the copy changes
    }

    static void IncreaseRef(ref int x)
    {
        x += 10;                        // the variable from the call changes
    }

    static void MinMax(int[] array, out int min, out int max)
    {
        min = max = array[0];           // out parameters must be given a value
        foreach (int v in array)
        {
            if (v < min) min = v;
            if (v > max) max = v;
        }
    }

    static void Main()
    {
        int a = 5;
        Increase(a);
        Console.WriteLine($"After Increase: {a}");
        IncreaseRef(ref a);
        Console.WriteLine($"After IncreaseRef: {a}");
        MinMax(new[] { 7, -3, 12, 0 }, out int mn, out int mx);
        Console.WriteLine($"min = {mn}, max = {mx}");
    }
}

Now it is clear how int.TryParse(text, out int number) works: the method returns a bool and writes the number through an out parameter. With arrays and objects a method gets a copy of the reference, so changes to the elements of an array remain visible even without ref.

Default parameters, params and overloading

using System;

class Program
{
    // overloading: the same name, different parameters
    static double Area(double a) => a * a;               // a square
    static double Area(double a, double b) => a * b;     // a rectangle

    // a default parameter value
    static string Greeting(string name, string language = "en") =>
        language == "fr" ? $"Bonjour, {name}!" : $"Hello, {name}!";

    // params: any number of arguments
    static int Sum(params int[] numbers)
    {
        int s = 0;
        foreach (int n in numbers) s += n;
        return s;
    }

    static void Main()
    {
        Console.WriteLine(Area(4));
        Console.WriteLine(Area(4, 2.5));
        Console.WriteLine(Greeting("Anna"));
        Console.WriteLine(Greeting("Anna", "fr"));
        Console.WriteLine(Greeting(language: "fr", name: "Mark"));   // named arguments
        Console.WriteLine(Sum(1, 2, 3));
        Console.WriteLine(Sum(10, 20, 30, 40));
        Console.WriteLine(Sum());
    }
}

The compiler chooses the method by the number and types of the arguments. Two methods cannot differ only in their return type.

Recursion: a method that calls itself

A recursive method solves a task by calling itself for a smaller problem. It must have a base case that is solved without a new call – otherwise the program crashes with a StackOverflowException error.

using System;

class Program
{
    static long Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1);
    static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b);      // Euclid's algorithm
    static string Binary(int n) => n < 2 ? n.ToString() : Binary(n / 2) + (n % 2);

    static void Main()
    {
        Console.WriteLine($"10! = {Factorial(10)}");
        Console.WriteLine($"GCD(84, 36) = {Gcd(84, 36)}");
        Console.WriteLine($"37 in binary = {Binary(37)}");
    }
}

More about recursion and about when a loop is better: Recursion.

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: easy

GCD and LCM

Read two natural numbers and print their greatest common divisor and least common multiple. Write the method static long Gcd(long a, long b).

Example 1

Input

12 18

Output

GCD = 6
LCM = 36

Example 2

Input

7 5

Output

GCD = 1
LCM = 35
TASK 02Difficulty: medium

Digital root

The digital root of a number is obtained by adding its digits, then the digits of the sum, until a one-digit number is left (98765 → 35 → 8). Write the recursive methods DigitSum and DigitalRoot and print the digital root of the number read (the number fits in a long).

Example 1

Input

98765

Output

8

Example 2

Input

493193

Output

2
Common mistakes and tips
  • A method is written inside the class, but outside the Main method.
  • A method that is not void must return a value in every case – otherwise you get the error "not all code paths return a value".
  • The local variables of one method are not visible in another; pass data through parameters and return values.
  • The words ref and out are written both in the method header and in the call.

Check your knowledge

Open the quiz

Methods in C#

1. What does void mean in a method header?




2. A method changes the value of an int parameter (without ref). What happens to the variable in the call?




3. What is an out parameter for?




4. What must every recursive method have?