All posts

· 11 min read

Path · Ch. 6

Methods: Split the Problem into Pieces

We learn to write functions in C# so we stop repeating code and a program reads like a list of steps. We cover parameters, return values, void, naming and scope, and then reorganize the guess-the-number game.

On this page
  1. The problem: repeated code
  2. How a function is put together
  3. Why is the function at the bottom?
  4. Function or method?
  5. More than one parameter
  6. Functions that return a result
  7. Naming functions
  8. Scope: who can see what
  9. Why splitting is worth it
  10. Mini-exercise: reorganize the guessing game
  11. Suggested solution
  12. What you learned
  13. Stuck?

If you did the exercises in the earlier chapters, you already have a Program.cs that doesn’t fit on the screen. It works, but to find where the number gets validated or where the hint is given, you have to read the whole thing top to bottom. And if the same piece of code shows up twice, every change has to be made twice.

Today you’ll learn to give a piece of code a name and use it as many times as you want. That’s called a function, and it’s the most important tool for keeping a program understandable as it grows.

The problem: repeated code

Look at this program:

Console.WriteLine("----------");
Console.WriteLine("Sales");
Console.WriteLine("----------");
Console.WriteLine("Coffee: 12");
Console.WriteLine("----------");
Console.WriteLine("Inventory");
Console.WriteLine("----------");
Console.WriteLine("Coffee: 40");
----------
Sales
----------
Coffee: 12
----------
Inventory
----------
Coffee: 40

The three lines that print a title are repeated. If tomorrow you want to swap the dashes for equals signs, you have to find and change every one of them. With two titles that’s easy; with twenty you’ll miss one.

Now the same idea with a function:

PrintTitle("Sales");
Console.WriteLine("Coffee: 12");
PrintTitle("Inventory");
Console.WriteLine("Coffee: 40");

static void PrintTitle(string title)
{
    Console.WriteLine("----------");
    Console.WriteLine(title);
    Console.WriteLine("----------");
}

The output is exactly the same. The difference is that the title lines now live in one place, and the first four lines of the program read almost like English: print the title “Sales”, write the sales, print the title “Inventory”, write the inventory.

How a function is put together

Let’s go piece by piece through static void PrintTitle(string title):

  • static: tells C# the function can only use what you pass to it. Further down, in the section on scope, you’ll see why that’s good for you.
  • void: the function does something but doesn’t give back a result. It prints and that’s it.
  • PrintTitle: the name. You call the function by that name.
  • (string title): the parameter. It’s a variable the function receives from outside. Here it’s a string called title.
  • What goes between the braces { } is the body: the code that runs every time you call the function.

To call the function you write its name, parentheses and the value you want to pass: PrintTitle("Sales");. That value is called an argument. Inside the function, title is "Sales" the first time and "Inventory" the next.

A function doesn’t run on its own. If you write one and never call it, its code never executes.

Why is the function at the bottom?

You may have noticed that we call PrintTitle on the first line, but the function is written at the end of the file. In Program.cs, C# reads the whole file before running it, so it already knows PrintTitle exists even though it’s further down. The program still runs top to bottom as always, and when it reaches a call it jumps into the function’s body, runs it and comes back to the next line.

The habit I recommend: main code first, then all the functions. That way, when you open the file, the first thing you read is the program’s steps, and if you want the details of a step, you scroll down to its function.

Function or method?

You’ll see both words. A function that lives inside a class is called a method, and in C# almost all code lives in classes. What you write in Program.cs without a class is technically a local function. Classes arrive in Part 2; today’s idea is the same in both cases, so day to day you’ll hear “method” for all of it.

More than one parameter

A function can take several parameters, separated by commas. Each one has its own type:

Greet("Ana", 3);

static void Greet(string name, int times)
{
    for (int i = 0; i < times; i++)
    {
        Console.WriteLine($"Hello, {name}");
    }
}
Hello, Ana
Hello, Ana
Hello, Ana

Order matters: the first argument goes to the first parameter and the second to the second. If you write Greet(3, "Ana"), the program doesn’t compile, because 3 isn’t a string. The compiler checks the types for you, just like with variables.

Functions that return a result

Often you don’t want the function to print anything. You want it to calculate something and hand it back. For that you replace void with the type of the result and use return:

Console.WriteLine(IsEven(4));
Console.WriteLine(IsEven(7));

static bool IsEven(int number)
{
    return number % 2 == 0;
}
True
False

static bool IsEven says this function returns a bool. return hands the value back to whoever called it. Since IsEven(4) turns into a bool, you can use it anywhere you’d use a bool, for example in an if:

int age = 18;

if (IsEven(age))
{
    Console.WriteLine("Your age is an even number.");
}

static bool IsEven(int number)
{
    return number % 2 == 0;
}
Your age is an even number.

return also ends the function right there. Whatever comes after it in the body doesn’t run. That lets you write functions with more than one exit:

int larger = Larger(8, 15);
Console.WriteLine($"The larger one is {larger}");

static int Larger(int a, int b)
{
    if (a > b)
    {
        return a;
    }
    return b;
}
The larger one is 15

If a is larger, the function returns a and it’s done. If not, it moves on to the next line and returns b. If a function promises to return an int, every path has to end in a return. If you delete return b;, the compiler tells you that not all code paths return a value, and it won’t compile.

(C# already ships Math.Max(8, 15), which does the same thing. We write it by hand here to see how return works.)

To sum up: void when the function does something, like printing; a type like int, bool or string when the function calculates something and gives it back.

Naming functions

Functions in C# are written in PascalCase: every word starts with a capital letter, including the first. PrintTitle, CalculateTotal, AskForNumber. Parameters follow the variable rule, camelCase: name, unitPrice.

Use a verb, because a function does something: CalculateTotal says more than Total. Functions that return a bool read well as a question: IsEven, HasBalance. A good name saves you from opening the function to find out what it does.

Scope: who can see what

Each function has its own space. A variable you declare inside a function only exists there:

int total = Add(2, 3);
Console.WriteLine(total);
Console.WriteLine(result);

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

This program doesn’t compile:

.../Program.cs(3,19): error CS0103: The name 'result' does not exist in the current context

The numbers in parentheses are the line and the column: line 3, where you try to print result.

result is born when Add starts and disappears when it ends. Outside, it doesn’t exist. What comes out of the function is the value it returns with return, and that’s why we store it in total. Delete the third line and the program prints 5.

It works the other way too: because of static, the function can’t see the main program’s variables either.

string name = "Ana";
Greet();

static void Greet()
{
    Console.WriteLine($"Hello, {name}");
}
.../Program.cs(6,33): error CS8421: A static local function cannot contain a reference to 'name'.

The fix is to pass in what it needs as a parameter:

string name = "Ana";
Greet(name);

static void Greet(string name)
{
    Console.WriteLine($"Hello, {name}");
}
Hello, Ana

Notice there are two name variables: the main program’s and Greet’s parameter. They share a name but they’re different variables; the call copies the value from one to the other. This is exactly what we want from static: by looking only at the function’s first line you know everything it uses. If you remove static, this error goes away and the function could read any variable in the program, which gets hard to follow as the file grows. That’s why on this path we always write static.

Why splitting is worth it

You’ve already seen two reasons. The first is not repeating yourself: if the code lives in one place, you fix it in one place. The second is reading better: a program made of calls with good names makes sense before you look at the details.

There’s a third one you notice when something breaks. A small function that gets its data through parameters and returns a result can be checked on its own: you call IsEven(7) and see whether it says False. When a hundred-line program doesn’t work, finding the bug is much easier if it’s split into pieces you can check one at a time.

Mini-exercise: reorganize the guessing game

Here is the guess-the-number game from chapter 4, the way it ended up:

int secret = Random.Shared.Next(1, 101);
int attempts = 0;
int guess = 0;

Console.WriteLine("I picked a number from 1 to 100. Guess it.");

while (guess != secret)
{
    Console.Write("Your guess: ");

    if (!int.TryParse(Console.ReadLine(), out guess))
    {
        Console.WriteLine("That is not a number. Try again.");
        continue;
    }

    attempts++;

    if (guess < secret)
    {
        Console.WriteLine("Higher.");
    }
    else if (guess > secret)
    {
        Console.WriteLine("Lower.");
    }
}

Console.WriteLine($"You got it in {attempts} guesses.");

Your task is to pull out two functions:

  1. AskForNumber: takes the message shown to the player, keeps asking until they type a valid number and returns it as an int.
  2. GetHint: takes the guess and the secret number, and returns the hint text ("Higher." or "Lower."). It doesn’t print anything; it only returns the text. The main loop only calls it when the guess is wrong.

When you’re done, the main loop should fit in a few lines. If you wrote your own version in chapter 4, do the same to yours.

Suggested solution

int secret = Random.Shared.Next(1, 101);
int attempts = 0;
int guess = 0;

Console.WriteLine("I picked a number from 1 to 100. Guess it.");

while (guess != secret)
{
    guess = AskForNumber("Your guess: ");
    attempts++;

    if (guess != secret)
    {
        Console.WriteLine(GetHint(guess, secret));
    }
}

Console.WriteLine($"You got it in {attempts} guesses.");

static int AskForNumber(string message)
{
    while (true)
    {
        Console.Write(message);
        if (int.TryParse(Console.ReadLine(), out int number))
        {
            return number;
        }
        Console.WriteLine("That is not a number. Try again.");
    }
}

static string GetHint(int guess, int secret)
{
    if (guess < secret)
    {
        return "Higher.";
    }
    return "Lower.";
}

The game behaves exactly like the one in chapter 4. The secret number changes every time, so yours will be different. This is an example game where the secret was 43:

I picked a number from 1 to 100. Guess it.
Your guess: 50
Lower.
Your guess: 25
Higher.
Your guess: hello
That is not a number. Try again.
Your guess: 37
Higher.
Your guess: 43
You got it in 4 guesses.

A few things to notice. AskForNumber has a while (true) and the only way out is the return, which hands back the number and ends the function at once. Since text that isn’t a number never reaches attempts++, “hello” doesn’t count as an attempt, and the continue from chapter 4 is no longer needed. And GetHint doesn’t print: it returns the text and the main program decides what to do with it. If tomorrow you want to show the hint some other way, GetHint doesn’t change.

If you have time left, add a static bool PlayAgain() function that asks “Another game? (y/n)” and returns true if the player types y, and use it to repeat the whole game.

What you learned

  • A function gives a name to a piece of code so you can use it as many times as you want.
  • Parameters are the input; return is the output.
  • void when the function does something; a type when it calculates and returns a value.
  • In Program.cs you can call a function that’s written further down. Keep the main code at the top and the functions at the end.
  • Functions are named in PascalCase, with a verb.
  • A function’s variables only exist inside it, and with static the function only sees what you pass it.

In the next chapter we talk about errors: how to read an exception, how to catch it and how to use the VS Code debugger to watch your program step by step.

Stuck?

If a function won’t compile or you don’t understand why it returns what it returns, DM me on Instagram or ask in the Discord community. Paste your code and the error you get, and we’ll work through it.