This post will tell you about the different ways C# allows you to pass arguments to a method.
Named Arguments
This is a beautiful C# language feature which allows you to pass method arguments in any order you want. Extreeemely, useful if you have a method which has a long list of parameters.
// Define a method
public void sum(int x, int y) {}
// Call your method with named args in any order you want!
sum(y: 2, x:3)
Optional Arguments
Optional arguments is another great part of C# which allows you to set default values for a method parameter. This means you can call this method without specifying a value for this parameter unless you want to give it a value other than the default.
public static void printName(string name, bool uppercase = false) {
if (uppercase) {
Console.WriteLine(name.ToUpper());
} else{
Console.WriteLine(name);
}
}// call your method with and without the optional argument
printName("imposter", true); // prints: IMPOSTER
printName("imposter"); // prints: imposter
Passing arguments by reference — using ref
C# has a keyword called ref
which is used to pass arguments by reference to a method. Passing an argument by reference means that any changes to that variable within the method will affect that variable outside the method as well.
public static void increment(ref int number) {
number++;
}// Use ref keyword to pass your counter variable by reference
int counter = 0;
increment(ref counter);
Console.WriteLine(counter); // prints: 1
Note: you must specify the ref keyword in the method signature and also the method invocation. If you don’t do this, you’ll get a compilation error.
Passing arguments by reference — using out
Another way you can pass arguments by reference is using the C# out
keyword. The syntax of this approach is very similar to ref
, the only difference is that with the out keyword you don’t need to initialise the variable beforehand. You do however, need to initialise the variable before using it.
public static void increment(out int number) {
number = 1; // note you need to initialise the variable before use
number++;
}// Use out keyword to pass your counter variable by reference
int counter; // note the variable is not initialised
increment(out counter);
Console.WriteLine(counter); // prints: 1
Passing unlimited parameters
Another brilliant side to the C# language is the ability to pass an indefinite amount of parameters to a method using the params
keyword. When you use this keyword it is as though you are capturing everything passed to the method inside an array.
public static int sum(params int[] numbers) {
int sum = 0;
foreach (var number in numbers) {
sum = sum + number;
}
return sum;
}// call your method with different number of arguments each time
Console.WriteLine(sum(1, 2, 3, 4)); // prints 10
Console.WriteLine(sum(2, 4, 6)); // prints 12
Tips:
- Methods should not have more than one
params
array - If a method has multiple arguments,
params
should be the last