Start learning free

LESSON 27 OF 347 · FUNCTIONS I

Functions in C#: Defining and Calling Methods

Lesson Read the full explanation

A function is a container for a few lines of code that perform a specific task.

Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.

Here's how a function definition looks like in C#:

returnType functionName() {
	// function body (where all the instructions are written)
}

There are two main components of a function:

1. The function header:

It consists of:

  • returnType which is the type of the value returned by the function
  • functionName is the function's name, a unique identifier we use to refer to the function
  • Parentheses (()). We'll learn more about their use in next lessons


2. The function body:

This is the code that C# executes whenever the function is called.

It consists of one or more C# statements placed inside curly brackets {} (where we have our C# comment).

Here's an example of a function:

void sayHello() {
	Console.WriteLine("Hello World");
}

The return type of this function is void, which means the function is not returning any value. We'll learn more about this in future lessons.

Notice that we indented (added one tab before) our Console.WriteLine("Hello World");.

Indentation is not mandatory like in Python, but we use it to make our code easier to read.


Calling a function

If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.

That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.

The code inside a function body runs, or executes, only when the function is called.

You can call or invoke a function by typing its name followed by parentheses, like this:

// Function declaration:
void sayHello() {
	Console.WriteLine("Hello World");
}
	
// Function call:
sayHello(); // Output: Hello World

All of the code inside the function body will be executed every time the function is called.

In our example, each time the function is called it will print out the message Hello World on the dev console.

We can call a function as many times as it is needed.


Console.WriteLine, var & PascalCase:

A few C# habits you'll see throughout the coding tutorials: you print with Console.WriteLine(...), you can let C# infer a variable's type with var instead of writing it out, and method names use PascalCase — each word capitalized, like MyMethod.

void SayHello() {
    var message = "Hello World"; // type inferred as string
    Console.WriteLine(message);
}

Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    C# · FUNCTIONS I

    Functions in C#, explained

    What a function is

    A function is a named container for a few lines of code that perform one task. Instead of writing everything in one long run of statements, you split a program into small pieces, give each piece a name, and run a piece whenever you need it. The program becomes easier to read, to change and to reuse.

    In C# a function is usually called a method, because it belongs to a class. The lessons show the methods on their own, and the editor around them takes care of the rest of the program.

    The shape of a method

    A method definition has a header and a body:

    returnType FunctionName() {
        // body: the statements to run
    }
    
    • The return type says what kind of value the method gives back. void means it gives back nothing.
    • The name identifies the method. C# style is PascalCase, with each word capitalized: SayHello, not sayHello.
    • The parentheses hold the method's inputs. They're empty for now, and a later lesson fills them in.
    • The body is the code between the curly braces. It's customary to indent it one level so the structure is easy to see. C# doesn't require the indentation the way Python does, but everyone does it.

    The lesson's methods are also marked public, an access modifier that says other code may use the method. Here is a complete one:

    public void SayHello() {
        Console.WriteLine("Hello World");
    }
    

    Defining is not running

    If you only define SayHello, nothing is printed. A definition tells C# that the method exists and what it does. The body runs only when the method is called, which means writing its name followed by parentheses:

    SayHello();   // prints: Hello World
    SayHello();   // prints: Hello World
    

    You can call a method as many times as you like, and every call runs the whole body from the first statement to the last. The parentheses matter. Writing SayHello; by itself is a compile error, because the bare name doesn't make a call.

    Small C# habits used in the tutorials

    • You print with Console.WriteLine(...), which writes its argument and then starts a new line.
    • var lets the compiler work out a local variable's type from its value. With var message = "Hello World";, message is a string. The type is still fixed at compile time; you just don't write it out.
    • Methods are written in PascalCase, as above.
    public void SayHello() {
        var message = "Hello World";   // type inferred as string
        Console.WriteLine(message);
    }
    

    The exercise, step by step

    The editor starts with an empty MainFunction, the place where the program's work happens. The task has three parts.

    1. Define the method. Above MainFunction, write public void SayHello() followed by a pair of braces. It's void because it prints a message instead of handing a value back.
    2. Fill in the body. Between the braces, call Console.WriteLine("Hello everybody!");. This line runs every time the method is called.
    3. Call it. Inside MainFunction, write SayHello();. Without this line the program would print nothing, because defining a method never runs it.

    Together:

    public void SayHello() {
        Console.WriteLine("Hello everybody!");
    }
    
    public void MainFunction() {
        SayHello();
    }
    

    Running MainFunction prints Hello everybody! once. Adding a second SayHello(); line would print it twice.

    Common mistakes

    • Defining but never calling. The most common reason a new method seems to do nothing.
    • Forgetting the parentheses on a call. SayHello; doesn't compile.
    • Leaving out the braces. The body must be wrapped in { }. Without them the print line isn't part of the method.
    • Misspelling the name or its capitalization. C# is case-sensitive, so sayhello() and SayHello() are different names, and calling the wrong one is a compile error.

    The order in which methods are defined inside a class doesn't matter to the compiler: a method can call another one that appears further down. What matters is the order of the statements inside a body, which run from top to bottom.

    Key takeaways

    • A method is a named block of code: return type, name, parentheses, then a body in braces.
    • void means the method returns nothing.
    • Defining a method stores it; calling it with Name(); runs it.
    • Every call runs the whole body, so one definition can serve many calls.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free