Parameters are variables that a function can receive when it is invoked and are defined in the function declaration.
Parameters allow functions to be more reusable and modular (as they allow different data to be passed to the same function).
If you want to learn more about Function Parameters
consult the Introduction to Programming Course read more
Value and Reference Parameters
Value Parameters
Value parameters are the most common. When parameters are passed by value, a copy of the value is passed to the function (which means that any modification inside the function does not affect the original value).
public void Increment(int number)
{
number++;
Console.WriteLine(number); // Displays 6
}
int value = 5;
Increment(value);
Console.WriteLine(value); // Displays 5
Reference Parameters
Passing parameters by reference allows the function to modify the original value of the variable that we have passed to the function. This is achieved using the ref
keyword.
public void Increment(ref int number)
{
number++;
}
int value = 5;
Increment(ref value);
Console.WriteLine(value); // Displays 6
in and out Parameters
Out Parameters
out
parameters are similar to ref
parameters, but they are primarily used to return multiple values from a function. It is mandatory to assign a value to the out
parameter within the function before it ends.
public void GetValues(out int a, out int b)
{
a = 1;
b = 2;
}
int x, y;
GetValues(out x, out y);
Console.WriteLine($"x: {x}, y: {y}"); // Displays x: 1, y: 2
In Parameters
in
parameters allow passing arguments by reference but ensure that they will not be modified by the function.
public void ShowValue(in int number)
{
Console.WriteLine(number);
}
int value = 5;
ShowValue(value); // Displays 5
Optional Parameters
C# allows defining optional parameters, which are those that have a default value and can be omitted when calling the function.
public void Greet(string name = "World")
{
Console.WriteLine($"Hello, {name}!");
}
Greet(); // Displays "Hello, World!"
Greet("Luis"); // Displays "Hello, Luis!"
Named Parameters
Named parameters allow explicitly specifying the names of the parameters when calling a function, allowing some optional parameters to be omitted.
public void CreatePerson(string name, int age, string city = "Unknown")
{
Console.WriteLine($"{name}, {age} years, {city}");
}
CreatePerson(age: 30, name: "Ana"); // Displays "Ana, 30 years, Unknown"
Variadic Parameters
Variadic parameters allow passing a variable number of arguments to a function using the params
keyword. Only one params
parameter can be present and it must be the last in the parameter list.
public void PrintNumbers(params int[] numbers)
{
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
PrintNumbers(1, 2, 3, 4, 5); // Displays 1 2 3 4 5