Skip to content

Methods

The Course
•
25 min study

A method gives a name to a piece of work so you can use it whenever you need it. Methods let you solve one small problem at a time and then stop thinking about the details. C# names methods with a capital letter, as in TotalMinutes.

Declaring and calling

A method declaration states its return type, its name and its parameters. return ends the method and hands a value back to the caller. Calling a method means writing its name with arguments in parentheses; the call then stands for whatever the method returned.

In top-level programs like these, you can declare a method beside your statements. It's usual to put them at the bottom, and you can call them from above their declaration. The keyword static here is a safety rail: it stops the method from quietly reading variables that belong to the main program, so everything it uses must come in through its parameters.

Follow the values in and out C#
int planned = AddBreak(25);
Console.WriteLine(planned);
Console.WriteLine(AddBreak(planned));

static int AddBreak(int minutes)
{
    return minutes + 5;
}
Check your prediction
Text
30
35

minutes is the parameter, the name the method uses inside. 25 is the argument, the value this call supplies. Each call gets its own fresh minutes.

Returning versus printing

return gives a value to the caller, and the caller decides what to do with it. Console.WriteLine shows text to a person, and the rest of the program can't use it. A method that returns is more useful, because you can do more calculations with its answer. A method that returns nothing has the return type void.

void and return C#
PrintLine("Plan", TotalMinutes(30, 15));
PrintLine("Doubled", TotalMinutes(30, 15) * 2);

static int TotalMinutes(int reading, int practice)
{
    return reading + practice;
}

static void PrintLine(string label, int minutes)
{
    Console.WriteLine($"{label}: {minutes} minutes");
}
Check your prediction
Text
Plan: 45 minutes
Doubled: 90 minutes

The compiler checks every call. Calling TotalMinutes(30) is an error because an argument is missing, and so is string s = TotalMinutes(1, 2); because the result is an int. A method with a return type must return a value on every path through it, as this one fails to do:

Not every path returns C#
Console.WriteLine(Label(5));

static string Label(int minutes)
{
    if (minutes > 0)
    {
        return "Positive";
    }
}
Check your prediction
Text
error CS0161

Add a return statement at the end of Label to fix it.

Methods can decide

return ends the method right away, so you can deal with special cases first and then get on with the normal case. Methods that answer a yes-or-no question return bool, and their names often start with Is or Has. For a method that's a single expression, => is a shorter way to write the same thing.

Early return and a one-line method C#
Console.WriteLine(Describe(0));
Console.WriteLine(Describe(90));

static string Describe(int minutes)
{
    if (!IsValid(minutes))
    {
        return "Invalid";
    }
    return minutes >= 60 ? "Long" : "Short";
}

static bool IsValid(int minutes) => minutes >= 1 && minutes <= 180;
Check your prediction
Text
Invalid
Long

Your turn

Exercise

Convert minutes to hours and minutes

Write FormatDuration(int minutes), which returns a string. 95 should give 1h 35m, 60 should give 1h 0m, and 20 should give 0h 20m. Print the result for all three. The method must return the text, not print it.

Your workspace C#
Console.WriteLine(95);
Hint 1: the idea

Whole-number division gives the hours, and the remainder gives the leftover minutes.

Hint 2: a first step

Declare the method with return type string at the bottom of the file, and have it return a fixed piece of text so you can see the call working.

Show one solution
C#
Console.WriteLine(FormatDuration(95));
Console.WriteLine(FormatDuration(60));
Console.WriteLine(FormatDuration(20));

static string FormatDuration(int minutes)
{
    return $"{minutes / 60}h {minutes % 60}m";
}
Text
1h 35m
1h 0m
0h 20m

The method returns the text instead of printing it, so the caller decides what to do with it, and a check could compare it. / 60 gives whole hours and % 60 the minutes left over, which is why 60 gives 1h 0m.

Rewrite the method using =>. Then add a call using 0 and predict the output before you run it.

Was this article helpful?

Your response is saved on this device.