Method Calls

You can call other methods from within a method.

Methods are able to call other methods, and those methods can call even more methods. You can invoke multiple methods inside a single method. This makes our program expand like a tree growing upward, with the Main function acting as its root.

In English technical documents, call a method and invoke a method carry exactly the same meaning;

Calling syntax: MethodName(argument list). We will cover argument lists later.

Method invocation works exactly as shown in the image above. Calls stack layer by layer. Once a function finishes executing, control returns to where it was called, and the program continues running from that point.

Take a look at this example



class Program
{
    static void Main()
    {
        //Calculate formula (23+69)*5/(6-2)
        Program program = new Program();
        Console.WriteLine(program.CalculateExpression());
    }

    int CalculateExpression()
    {
        int result = Divide();
        return result;
    }

    int Add(int a, int b)
    {
        return a + b;
    }

    int Subtract(int a, int b)
    {
        return a - b;
    }

    int Multiply(int a, int b)
    {
        return a * b;
    }

    int Divide()
    {
        int res = Add(23, 69);
        return Multiply(res, 5) / Subtract(6, 2);
    }
}
Code language: C# (cs)

In the sample above, the Main function calls CalculateExpression. CalculateExpression then calls Divide. Inside Divide, we first run Add, followed by Multiply and Subtract, before finishing the division calculation.

Method Calls

Leave a Reply

Your email address will not be published. Required fields are marked *