Organizing Code into Methods

Write your own C# methods with parameters and return values, call them with arguments, and keep each one to a single job.

Apprentice · C# · Updated

After this lesson you can

  • Write a method with parameters and a return type
  • Call a method with arguments and use the value it returns

Key takeaways

  • A method has a return type, a name in PascalCase, parameters in parentheses and a body in curly braces.
  • return ends the method and hands back a value that must match the return type. A void method gives nothing back.
  • Call a method by its name with the arguments in parentheses, in the same order as its parameters. Their names don't need to match.
  • Store a returned value in a variable, or use it directly in an expression such as Add(costOfGum, costOfSnack) + 1.75m.
  • Give each method one job and a name that says what it does, such as CalculateFinalScore, not DoStuff.

When the same steps appear in several places, you put them in a method and call it instead. That keeps your code DRY (Don't Repeat Yourself): if the steps change, you change them in one place, and you can't miss a copy.

The parts of a method

A method has four parts:

int Add(int firstNumber, int secondNumber)
{
    return firstNumber + secondNumber;
}
Part Here What it is
Return type int The type of value the method gives back
Name Add What you call it by. C# method names use PascalCase: each word starts with a capital.
Parameters int firstNumber, int secondNumber The values the method needs, each with a type and a name, in parentheses
Body { return firstNumber + secondNumber; } The steps, between curly braces

return ends the method and hands back the value after it. That value must match the return type.

Calling a method

To call a method, write its name followed by parentheses. Inside the parentheses go the values for its parameters, in the same order. The values you pass are called arguments.

In a C# program written as top-level statements, you call methods at the top and write them at the bottom of the file:

DisplayGreeting("Joseph");
DisplayGreeting("Maria");

void DisplayGreeting(string name)
{
    Console.WriteLine("Good morning, " + name);
}
Good morning, Joseph
Good morning, Maria

Each call runs the method's body with name set to that call's argument. The method is written once and runs twice.

Methods that don't return a value

DisplayGreeting prints something, but gives nothing back. Its return type is void, which means "no value". A call to a void method is a statement on its own line, as above.

Using the value a method returns

When a method returns a value, store it in a variable, or use it directly in an expression:

decimal costOfGum = 1.25m;
decimal costOfSnack = 2.50m;

decimal totalCost = Add(costOfGum, costOfSnack);
Console.WriteLine("Total: quot; + totalCost);
Console.WriteLine("With a drink: quot; + (Add(costOfGum, costOfSnack) + 1.75m));

decimal Add(decimal firstPrice, decimal secondPrice)
{
    return firstPrice + secondPrice;
}
Total: $3.75
With a drink: $5.50

The arguments' names don't need to match the parameters' names. costOfGum is passed in, and inside the method its value is called firstPrice.

Methods without parameters

Some methods need no input. Their parentheses are empty, in the method and in the call:

Console.WriteLine("You rolled a " + RollDie());

int RollDie()
{
    return Random.Shared.Next(1, 7);
}

Random.Shared.Next(1, 7) picks a whole number from 1 up to, but not including, 7. Run it a few times: the number changes.

One job per method

Each method should do one thing, and its name should say what. CalculateFinalScore and DisplayTeamScores are good names; DoStuff isn't. A method that does one thing is easy to name, easy to test, and easy to reuse. This idea has a name you'll meet again: the Single Responsibility Principle.

Methods in a class

Methods can also live inside a class: a named container for related methods (and, later, data). You'll learn about classes properly in a later chapter. For now, here's what one looks like, because the exercises use them:

Console.WriteLine(Scoreboard.FinalScore(12, 14, 6, 7));

static class Scoreboard
{
    public static int FinalScore(int q1, int q2, int q3, int q4)
    {
        return q1 + q2 + q3 + q4;
    }
}
39
  • You call it with the class's name, a period, and the method's name: Scoreboard.FinalScore(...), just like Math.Round(...).
  • public lets code outside the class call the method.
  • static means you call the method on the class itself. Methods like this are the kind you'll write for now.

Check yourself

2 questions to try on the lesson page.

So what

A method turns a few lines into a named job you can call from anywhere: parameters bring values in, return sends a result out, and the code that calls it stays short and clear.

Key terms

Cheat sheets