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
Section titled “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);AddNumbersis the name of the method we defined earlier.- We call it by writing its name followed by parentheses
(). - Inside the parentheses, we can provide the arguments
5and10, which correspond to the parametersaandbin the method definition. - The method returns the sum of
aandb, which is15in this case. - We store the returned value in the variable
sum, which has the typeint.
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.