Functions in C#

Functions are central in C#. We’ll learn about functions with a few different examples.

using System;

class Program
{
    // Here's a function that takes two ints and returns
    // their sum as an int.
    static int Plus(int a, int b)
    {
        // C# allows implicit returns, but we'll use an explicit return
        // for consistency with the original example.
        return a + b;
    }

    // In C#, we don't need to specify the type for each parameter
    // if they are of the same type.
    static int PlusPlus(int a, int b, int c)
    {
        return a + b + c;
    }

    static void Main()
    {
        // Call a function just as you'd expect, with
        // name(args).
        int res = Plus(1, 2);
        Console.WriteLine("1+2 = " + res);

        res = PlusPlus(1, 2, 3);
        Console.WriteLine("1+2+3 = " + res);
    }
}

To run the program, save it as Functions.cs and use the C# compiler to compile and run:

$ csc Functions.cs
$ mono Functions.exe
1+2 = 3
1+2+3 = 6

There are several other features to C# functions. One is multiple return values, which we can achieve using tuples or out parameters.

In C#, functions are defined using the static keyword when they belong to the class itself rather than an instance of the class. The Main method is the entry point of the program.

C# uses Console.WriteLine for printing to the console, which is similar to fmt.Println in the original example.

Unlike Go, C# uses curly braces {} to define function bodies and doesn’t use semicolons to end statements (although they are optional).

C# also supports method overloading, allowing multiple methods with the same name but different parameters, which wasn’t shown in this example but is a powerful feature of the language.