.NET Academy

Writing methods

Package code into reusable, named methods with parameters and return values.

12 min read

You will learn

  • Declare a method with parameters and a return type
  • Tell the difference between returning a value and printing it
  • Use void, expression-bodied methods and optional parameters
  • Call methods and use their results

Why methods?

As programs grow, you'll notice the same few lines appearing again and again. A method gives a block of code a name, so you can run it whenever you need it by calling that name.

Methods make code:

  • Reusable — write it once, call it anywhere.
  • Readable — CalculateTax(price) says what happens; the details live inside the method.
  • Testable — you can check a small method on its own. That's exactly how the exercises in this course are graded.

Anatomy of a method

int Add(int a, int b)
{
    return a + b;
}
//│  │    └──────── parameters: inputs, each with a type and name
//│  └───────────── the method's name (PascalCase)
//└──────────────── return type: the type of value it gives back

Calling it:

int sum = Add(2, 3);        // the arguments 2 and 3 become a and b
Console.WriteLine(sum);     // 5
Console.WriteLine(Add(10, Add(1, 1)));  // 12 — results can feed other calls

Parameters vs arguments

Parameters are the variables in the method's declaration (a, b). Arguments are the actual values you pass when calling it (2, 3).

return hands a value back

return does two things: it gives a value back to the caller, and it exits the method immediately.

string Classify(int age)
{
    if (age < 13) return "child";
    if (age < 20) return "teenager";
    return "adult";
}

The return type is a promise: a method declared as int must return an int on every path, or the compiler complains.

void — methods that just do something

When a method performs an action and has nothing to give back, its return type is void:

void PrintBanner(string title)
{
    Console.WriteLine(new string('=', title.Length));
    Console.WriteLine(title);
    Console.WriteLine(new string('=', title.Length));
}
 
PrintBanner("Report");

Return, don't print

Beginners often write void Add(int a, int b) { Console.WriteLine(a + b); }. It looks fine, but the result is stuck on the screen — you can't store it, compare it or pass it on. Prefer methods that return values, and let the caller decide what to do with them.

Expression-bodied methods

When a method is a single expression, use => for a compact form:

int Square(int x) => x * x;
bool IsAdult(int age) => age >= 18;

It means exactly the same as { return x * x; }.

Optional and named arguments

Give a parameter a default value to make it optional:

string Greet(string name, string greeting = "Hello") => $"{greeting}, {name}!";
 
Greet("Ada");                          // "Hello, Ada!"
Greet("Ada", "Welcome");               // "Welcome, Ada!"
Greet(greeting: "Hey", name: "Ada");   // named arguments, any order

Optional parameters must come after the required ones.

Overloading

Several methods can share a name if their parameters differ:

int Max(int a, int b) => a > b ? a : b;
int Max(int a, int b, int c) => Max(Max(a, b), c);

The compiler picks the right one from the arguments you pass.

Where do methods live?

In a small program with top-level statements (like ours), you can declare methods right in the file — they're called local functions. In bigger programs, methods live inside classes, which you'll meet in the OOP track:

class Calculator
{
    public static int Add(int a, int b) => a + b;
}
 
Console.WriteLine(Calculator.Add(2, 3));

Try it

Change Classify so 65+ returns "senior", then run it:

Program.cs
Loading editor…

C# runtime not loaded

Key takeaways

  • A method = return type + name + parameters + body.
  • return gives a value back and exits; void methods return nothing.
  • Prefer returning values over printing them inside the method.
  • => for one-liners, default values for optional parameters, overloads for variations.

Exercise

Complete the two methods. IsEven should return true when a number is even. Greet should return a greeting like "Hello, Ada!" — and use the greeting parameter when one is given, e.g. Greet("Linus", "Hi") → "Hi, Linus!".

Program.cs
Loading editor…

C# runtime not loaded

Hint 1

A number is even when the remainder after dividing by 2 is zero. The remainder operator is %: 7 % 2 is 1.

Hint 2

Return the comparison itself — `return number % 2 == 0;` — no if statement needed.

Hint 3

For Greet, string interpolation does all the work: $"{greeting}, {name}!"

Show solution
bool IsEven(int number) => number % 2 == 0;

string Greet(string name, string greeting = "Hello") => $"{greeting}, {name}!";

Console.WriteLine(IsEven(4));
Console.WriteLine(Greet("Ada"));

Quiz

4 questions · 3 correct to pass
  1. 1.What does a method with return type `void` give back to its caller?

  2. 2.Given `int Square(int x) => x * x;` — what is `Square(3) + 1`?

  3. 3.What's the difference between returning a value and printing it?

  4. 4.With `string Greet(string name, string greeting = "Hello")`, which call does NOT compile?

To complete this lesson

  • ○ Solve the exercise
  • ○ Pass the quiz (3/4 correct)