Methods

A method is a named block of code that performs one task. You define it once and call it whenever you need it, passing in values and getting a result back. Methods keep programs organised, remove repetition and let you think about one problem at a time.

Defining and calling a method

C#
PrintBanner("Weekly report");
PrintBanner("Totals");

static void PrintBanner(string title)
{
    string line = new string('*', title.Length + 4);
    Console.WriteLine(line);
    Console.WriteLine($"* {title} *");
    Console.WriteLine(line);
}
Output
*****************
* Weekly report *
*****************
**********
* Totals *
**********

The method's signature is static void PrintBanner(string title):

  • static — the method doesn't belong to a particular object (lesson 34). For now, write it on methods like these.
  • void — the return type; void means it returns nothing.
  • PrintBanner — the name, in PascalCase, usually a verb.
  • (string title) — the parameters: inputs, each with a type and a name.

In a file with top-level statements, methods go after the statements and can be called from anywhere above them.

Returning a value

A method with a return type other than void must hand back a value of that type with return. The caller can use the result like any other value:

C#
double area = CircleArea(2.5);
Console.WriteLine($"Area: {area:F2}");
Console.WriteLine($"Total: {CircleArea(1) + CircleArea(2):F2}");

static double CircleArea(double radius)
{
    return Math.PI * radius * radius;
}
Output
Area: 19.63
Total: 15.71

Every possible path through the method must return a value, or the compiler complains:

C#
Console.WriteLine(Sign(5));

static string Sign(int n)
{
    if (n > 0) return "positive";
    if (n < 0) return "negative";
}
Build error
Program.cs(3,15): error CS0161: 'Sign(int)': not all code paths return a value

return ends the method

return exits immediately, which makes it useful for guard clauses at the top of a method:

C#
Console.WriteLine(Describe(-3));
Console.WriteLine(Describe(0));
Console.WriteLine(Describe(42));

static string Describe(int n)
{
    if (n < 0) return "negative";
    if (n == 0) return "zero";
    return n % 2 == 0 ? "positive and even" : "positive and odd";
}
Output
negative
zero
positive and even

A void method can also use a bare return; to stop early.

Expression-bodied methods

When a method just returns a single expression, write it with =>:

C#
Console.WriteLine(Square(9));
Console.WriteLine(IsEven(7));
Console.WriteLine(FullName("Alan", "Turing"));

static int Square(int x) => x * x;
static bool IsEven(int n) => n % 2 == 0;
static string FullName(string first, string last) => $"{first} {last}";
Output
81
False
Alan Turing

Methods calling methods

Small methods combine into bigger ones. Each one is easy to understand and test on its own:

C#
int[] marks = [72, 88, 95, 61, 79];
PrintSummary(marks);

static void PrintSummary(int[] values)
{
    double avg = Average(values);
    Console.WriteLine($"Average: {avg:F1} ({Grade(avg)})");
}

static double Average(int[] values)
{
    int sum = 0;
    foreach (int v in values) sum += v;
    return (double)sum / values.Length;
}

static string Grade(double score) => score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    _ => "D",
};
Output
Average: 79.0 (C)

Methods inside a class

In larger programs, methods live inside classes. A static class is a simple container for related helper methods; call them with the class name in front. Classes must come after the top-level statements:

C#
Console.WriteLine(Temperature.ToFahrenheit(100));
Console.WriteLine(Temperature.ToCelsius(-40));

static class Temperature
{
    public static double ToFahrenheit(double celsius) => celsius * 9 / 5 + 32;
    public static double ToCelsius(double fahrenheit) => (fahrenheit - 32) * 5 / 9;
}
Output
212
-40

public makes the methods usable from outside the class (lesson 35). Lessons 31 onwards cover classes fully; there you'll also meet instance methods, which work on an object's own data.

Why use methods?

  • Reuse: write the logic once and call it from many places.
  • Readability: a good name like CalculateShipping explains what a block of code does.
  • Fewer bugs: fixing a bug in one method fixes it everywhere it's called.
  • Testing: small methods with inputs and outputs are easy to check (lesson 60).

A good method does one thing, has a name that says what, and is short enough to read without scrolling.

Try it yourself

Write a method IsPalindrome that ignores case and spaces, then test it on a few phrases.

Try it yourself · Program.cs
Edit the code, copy it into Program.cs and run it with dotnet run Program.cs (.NET 10 or later). How to set up .NET
Output
Racecar: True
Never odd or even: True
C sharp: False