Functions

Give a piece of code a name, hand it values, and get a result back.

Your C# code runs inside your browser tab. Nothing to install.

Defining and calling a function

A function is a named block of code. Defining it does not run it.

A function starts with the kind of value it gives back. void means it gives nothing back. By convention, C# function names start with a capital letter.

It runs when you call it, by writing its name followed by round brackets. A function can be called as many times as you like.

Example
void Greet() {
    Console.WriteLine("Welcome");
}

Greet();
Greet();

Giving a function values

A parameter is a variable that receives a value each time the function is called.

Parameters are listed in the brackets of the definition, each with its type.

The values you pass when calling are matched to the parameters in order.

Example
void Greet(string name) {
    Console.WriteLine("Welcome, " + name);
}

Greet("Asha");
Greet("Bilal");

Your turn: a function with a parameter

Write a function and call it twice.

Practice task

Write a function `ShowDouble` that takes a number and prints twice that number. Call it with 4, then with 10.

Your answer is run and checked in the lesson. Create a free account to try it.

Getting a result back

return hands a value back to the place where the function was called, and ends the function.

The word before the function's name says what kind of value it returns: int here, instead of void.

Printing shows a value on the screen. Returning gives it back to the program. They are different things.

Example
int Area(int width, int height) {
    return width * height;
}

int room = Area(4, 5);
Console.WriteLine(room);
Console.WriteLine(Area(2, 3) + 1);

Your turn: return a value

This function must give its answer back, not print it.

Practice task

Write a function `Larger` that takes two numbers and returns the bigger one. Print Larger(7, 3) and then Larger(2, 9).

Your answer is run and checked in the lesson. Create a free account to try it.