Methods

Methods #

In object-oriented languages, functions belonging to an object are called Methods. You can think of it like a function like other programming language.


The method declaration specifies return type, method name, and parameters.

int Add(int x, int y) {
    return x + y;
}

Console.WriteLine(Add(1, 2));

void means that the method does not return a value.

void Greeting(string name) {
    Console.WriteLine($"Hello {name}");
}

// output: Hello scalalang2
Greeting("scalalang2");

The Swap methods below do not work as expected.

Because the parameters are passed by value, sometimes this is called Call by Value

void Swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
}

int x, y;
x = 10;
y = 25;

Console.WriteLine("x:{0}, y:{1}", x, y); // x:10, y:25
Swap(x, y);
Console.WriteLine("x:{0}, y:{1}", x, y); // x:10, y:25

To make it work as call-by-reference, use the ref keyword.

void Swap(ref int a, ref int b) {
    int temp = a;
    a = b;
    b = temp;
}

int x, y;
x = 10;
y = 25;

Console.WriteLine("x:{0}, y:{1}", x, y); // x:10, y:25
Swap(ref x, ref y);
Console.WriteLine("x:{0}, y:{1}", x, y); // x:25, y:10