Skip to content

Beginner · Decisions, loops and methods · topic 8 of 43 · 30 min

Methods: write once, use many times

Explanation

A method is a named block of code that does one job. It can take inputs (parameters) and give back a result with return; void means it gives back nothing. Short methods can use the arrow form =>. Splitting a program into small, well-named methods makes it easier to read, test and fix.

Why methods?

You have already called methods that .NET gives you: Console.WriteLine, int.Parse and Math.Round. A method is a named block of code that does one job. When you write your own, you can reuse the steps by calling the name. If the GST rate changes, you fix one method instead of twenty copies.

Think of it like this: A method is like a pressure cooker. You put things in (parameters), close the lid, wait for the whistles, and get cooked food out (the return value). You do not think about the steam valve every time; you just use it.

The parts of a method

csharp
static decimal AddGst(decimal price, decimal rate)
{
    decimal gst = price * rate;
    return price + gst;
}
static: no object needed (module 4). decimal: the return type. AddGst: the name. (decimal price, decimal rate): the parameters.
PartMeaning
Return typeThe type of value the method gives back; void if it gives back nothing
NamePascalCase, usually a verb: CalculateTotal, PrintReceipt, IsValidPin
ParametersInputs, each with a type and a name, separated by commas
BodyThe statements in { }
returnEnds the method and hands the value back to the caller

Calling a method

csharp
decimal total = AddGst(1000m, 0.18m);
Console.WriteLine(total);                 // 1180.00
Console.WriteLine(AddGst(500m, 0.05m));   // 525.00

static decimal AddGst(decimal price, decimal rate)
{
    return price + price * rate;
}
In a top-level Program.cs you can write methods below your statements; they become local functions. In a class, methods go inside the class.

Values you pass when calling (1000m, 0.18m) are called arguments. They are copied into the parameters (price, rate) in the same order.

void methods

csharp
PrintLine('=', 20);
Console.WriteLine("  BILL");
PrintLine('=', 20);

static void PrintLine(char symbol, int length)
{
    Console.WriteLine(new string(symbol, length));
}
A void method does a job (printing) but returns nothing. new string('=', 20) makes a string of 20 = signs.

Expression-bodied methods

csharp
static int Square(int n) => n * n;
static bool IsAdult(int age) => age >= 18;
static void Greet(string name) => Console.WriteLine($"Hi {name}");
When the body is a single expression, => replaces the braces and the return keyword.

Every path must return

csharp
static string Result(int marks)
{
    if (marks >= 40)
        return "Pass";
    // error CS0161: not all code paths return a value
}
The compiler checks that every possible path ends with return. Add return "Fail"; at the end.

Local variables and scope

A variable declared inside a method is local: it exists only while the method runs and only inside its braces. Two methods can both have a variable named total without any clash. This is called scope: the region of code where a name can be used.

Returning more than one value with a tuple

csharp
var (each, left) = SplitBill(1000, 3);
Console.WriteLine($"Each pays {each}, {left} rupee left");

static (int Each, int Left) SplitBill(int total, int people)
    => (total / people, total % people);
A tuple groups several values. Shows Each pays 333, 1 rupee left.

Recursion, briefly

csharp
static long Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1);
Console.WriteLine(Factorial(5));   // 120
A method that calls itself is recursive. It must have a stopping case (n <= 1), or it runs until a StackOverflowException.

Common mistakes and fixes

  • Printing instead of returning: a method named CalculateTotal that only prints cannot be used in further sums. Return the value and let the caller print.
  • Forgetting to use the return value: AddGst(price, rate); on its own line throws the answer away. Store it: price = AddGst(price, rate);
  • Methods that do five jobs: split them. A good method fits on one screen and its name says exactly what it does.
  • Wrong argument order: AddGst(0.18m, 1000m) compiles but gives the wrong answer. Named arguments (next topic) help.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Methods: write once, use many times · 1/7

Methods

In this lesson you will write your own methods: named blocks of code that do one job.

Prefer a video by a teacher? Find free videos on “C# methods parameters return values static methods beginners” on YouTube ↗

In real life: A Zomato-style delivery charge

A food delivery app charges delivery by distance and waives it for big orders. Putting the rule in one method means the pricing team can change it in one place, and testers can check it with many values.

csharp
Console.WriteLine(DeliveryCharge(2.5, 150m));   // 25
Console.WriteLine(DeliveryCharge(7.0, 300m));   // 55.0
Console.WriteLine(DeliveryCharge(7.0, 600m));   // 0

static decimal DeliveryCharge(double km, decimal orderValue)
{
    if (orderValue >= 499m) return 0m;    // free delivery on big orders
    if (km <= 3) return 25m;
    return 25m + (decimal)Math.Ceiling(km - 3) * 7.5m;
}
Math.Ceiling rounds up, so 4 extra km cost 4 x 7.5 = 30.0, giving 55.0 (a decimal keeps the digits after the point from 7.5m). The rule is made up for practice.

Practice (0/4 done)

Task 1 · Question

static int Twice(int n) => n * 2; What does Console.WriteLine(Twice(4) + 1); print?

Task 2 · Question

Which method header is correct for a method that returns nothing?

Task 3 · Question

Why does this not compile? static bool IsEven(int n) { if (n % 2 == 0) return true; }

Task 4 · Practice

Write three methods for a school report: Total(int a, int b, int c) returns the total, Percentage(int total, int maxTotal) returns a double percentage, and Grade(double percent) returns "A" (90+), "B" (75+), "C" (40+) or "F" using a switch expression. Call them for marks 85, 92 and 78 out of 300.

Quick quiz

Question 1

1.What is the difference between a parameter and an argument?

Question 2

2.What does return do?

Question 3

3.Which is a good method name in C#?

Question 4

4.A variable declared inside a method can be used...

Question 5

5.What is needed for a recursive method to stop?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is the difference between a parameter and an argument?

Answer: A parameter is the name in the method header; an argument is the value passed when calling

Parameters are the placeholders; arguments are the actual values.

What does return do?

Answer: Ends the method and gives a value back to the caller

return ends the method immediately and hands back the value.

Which is a good method name in C#?

Answer: CalculateTotal

C# methods use PascalCase and usually start with a verb.

A variable declared inside a method can be used...

Answer: Only inside that method (its scope)

Local variables exist only inside the method that declares them.

What is needed for a recursive method to stop?

Answer: A base (stopping) case that does not call itself

Without a base case, the calls never end and the stack overflows.

A variable is declared with const inside a function. Where can it be used?Related

Answer: Only inside that function

let and const are block-scoped: they live only inside their { }.

From Functions

What does void mean in a method declaration?Related

Answer: The method returns no value

void methods do not return a value.

From Methods: parameters, return values and overloading

A non-void function ends without return on one branch, and the caller uses the result. This is…Related

Answer: Undefined behaviour

gcc -Wall warns about it.

From Functions

What does void as a return type mean?Related

Answer: The function returns nothing

void functions do their job without giving a value back.

From Functions: declare, define, call and return

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Decisions, loops and methods” before its exam: Parameters in depth: optional, named, ref, out, params, overloading.
  2. Module 2 exam: Decisions, loops and methods · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Arrays, strings and null. 43 topics left in the course before the final exam.

← Previous: Loops: for, while, do-while and foreach