Methods

There isn't too much to add when it comes to methods. They still have a return type, followed by a name, followed by parentheses containing the argument list. There are three (3) keywords that are worth mentioning here, though. ref, out, and params.

ref is used to qualify arguments as being passed by reference, not by copy. This is functionally identical to the & notation you would have used from C++. The prerequisite here is that the argument must be initialized. Changes made to the argument within this method will modify the variable from the calling method.

out is functionally very similar, except there's no prerequisite that the argument be initialized. Arguments that are passed as out must be assigned a value by the called method.

public void myRefMethod(ref int alpha)
{
alpha = 27;
}

public void myOutMethod(out int alpha)
{
alpha = 216;
}

public static void Main()
{
int first = 100;
int second;

myRefMethod(ref first); // note the "ref" keyword usage here
myOutMethod(out second); // note the "out" keyword usage here
// At this point in the code, first == 27 and second == 216
}


params (a "parameter array") can be very useful, as it allows for a variable number of arguments to be passed to the same method. A params must come at the end of your argument list, and it must be a 1-dimensional array of things. Let's take a look at how we might use this in our programs:

public void simpleAdd(int increment, params int[] array)
{
for (int i = 0; i < array.Length; i++)
array[i] += increment;
}

public static void Main()
{
int[] myArray = { 0, 1, 2, 3, 4 };

simpleAdd(100, myArray); // myArray will then contain 100, 101, 102, 103, 104
simpleAdd(5, 1, 2, 3); // "array" == { 1, 2, 3 } (although not meaningfully returned)
}


Thus, params can be a quicker way to send over a variable number of arguments, as opposed to stuffing them into a container first before passing. Which will require some legwork upfront from whoever uses this method. The only legwork you should look forward to doing is squats!