Method calling

To call a method on an object in C#, we use this syntax:

returnType value = object.MethodName(arguments);

Or, if it’s a static method belonging to a class, we use:

returnType value = ClassName.MethodName(arguments);

We don’t have to store the return value in a variable; we can call the method without capturing its return value:

object.MethodName(arguments);
ClassName.MethodName(arguments);

Our example from before

In the last chapter, we created this function:

public static int AddNumbers(int a, int b)
{
    return a + b;
}

The full code looked like this:

using System;
class Program
{
    public static int AddNumbers(int a, int b)
    {
        return a + b;
    }

    static void Main()
    {
        int sum = AddNumbers(5, 10);
        Console.WriteLine(sum); // Output: 15
    }
}

Let’s focus on this line:

int sum = AddNumbers(5, 10);

When we run this program, it will output 15 to the console. That’s because the AddNumbers method returned 15, which was stored in sum and then printed.