Parameters in Depth
Pass-by-value
A copy of a variable is passed to the method.
Any changes made to the value within the method does not affect the value outside of it.
static void Main(string[] args)
{
int num = 15;
Console.WriteLine("Number (outside the function): {0}", num);
PrintSquare(num);
Console.WriteLine("Number (outside the function): {0}", num);
Console.Read();
}
static void PrintSquare(int number)
{
number = number * number;
Console.WriteLine("Number (inside the function): {0}", number);
}
Output:
-------
Number (outside the function): 15
Number (inside the function): 225
Number (outside the function): 15Pass-by-reference
A reference to a variable is passed.
The
refkeyword is used
If the value is changed within the method, it will be changed outside as well.
Out-parameters
An
outparameter is used to take a value from inside-to-outside of a method.Whereas a
refparameter works both ways.
Especially useful when you need to return more than one value from a method.
Any values assigned to the parameters outside of the method will be overwritten.
Default Parameters
A default value for select parameters can be passed
Any non-default parameters must come before default parameters in the method definition
Last updated