Introduction to Methods: an overview

A method is a named block of reusable code; you've been calling them since your first program.

Novice · C# · Updated

After this lesson you can

  • Explain what a method is and why programs are split into methods

Key takeaways

  • A method is a named block of code that does one job. You write it once and call it by name whenever you need that job done.
  • Console.WriteLine, Math.Round and int.Parse are methods. To use one, you only need its name, what to give it and what it gives back.
  • Other languages say function; in C# every function belongs to a class or the program, so it's called a method.
  • When you catch yourself copying the same lines, put them in a method instead. That's DRY, Don't Repeat Yourself, and it leaves one place to fix.

A method is a named block of code that does one job. You write it once, give it a name, and then run it, or call it, by that name whenever you need the job done.

As you write programs, you'll notice that you often write the same lines of code again, or copy and paste them. That's a sign there's a repeatable pattern, and a method is how you capture it: instead of copying the lines, you put them in a method and call it.

You've already used methods

Every program you've written so far calls methods that someone else wrote:

Console.WriteLine("Rounding 7.6:");
Console.WriteLine(Math.Round(7.6));
Console.WriteLine(int.Parse("42") + 1);
Rounding 7.6:
8
43
  • Console.WriteLine writes a line in the terminal.
  • Math.Round takes a number and gives back the nearest whole number.
  • int.Parse takes text and gives back an int.

Each one does one job, and you didn't need to know how it does it. You only needed its name, what to give it, and what it gives back. In this chapter you'll write methods of your own that work the same way.

Method or function?

Other languages call these functions. In C#, every function belongs to something larger: a class, or the program itself. A function that belongs to something is called a method, so C# developers say method. When you read about functions in JavaScript or Python, it's the same idea.

Why split a program into methods?

  • No repeated code. Write the steps once, call them many times. Developers call this DRY: Don't Repeat Yourself.
  • One place to fix. When the steps change, you change them in one method, not in every copy.
  • Code that explains itself. A call like DisplayTeamScores(...) says what happens; the details live inside the method.
  • Smaller pieces. A long program is easier to understand, test and debug as a set of small methods, each doing one thing.

Check yourself

1 question to try on the lesson page.

So what

Methods are how programs grow without becoming a tangle: each job gets a name and a single home. The next lessons show the problem they solve, then how to write your own.

Key terms

Cheat sheets