In .NET there are 4 different types of parameter modifiers, some used more than others, and each used for a specific purpose.
None - This is when the parameter is not marked with any modifier. The value is passed by value, meaning that the parameter is a copy of the original.
out - An output parameter must be assigned by the method being called. The value is passed by reference, meaning that the parameter is the original, so any changes in the method will effect the original value. If the output parameter is not assigned by the called method a compilation error will occur.
ref - The caller assigns the value, which can then be reassigned by the called method. The value is passed by reference. There is no compiler error if the called method does not assign a value to the ref parameter.
params - This allows you to send in multiple number of arguments as a single parameter. This must the last parameter and a method can only have one params modifier. This modifier is used a lot within the base class libraries, but you will most likely not have an everyday use for it.
Here is an example of each modifier used.
No Modifier:
This is the most commonly used modifier.
|
|
Here we can see that since there is no modifier on the parameters for ChangeNumbers(x, y) the parameters are passed by value, leaving the original values of x and y in Main() unchanged.
out:
The main purpose of using the out parameter is to get multiple return values from a method call.
|
|
All three values are assigned a value in the GetValues() and can be used in the Main method. In the GetValues() method all three values must be initialized, if not then an error will be thrown.
ref:
|
|
The ref modifier is very similar to the out parameter, but there are a few differences. A ref parameter must be initialized before passing to a method, if it is not initialized then an unassigned parameter is passed. Also inside the method it is not mandatory to change the value of the ref parameter.
params:
|
|
Even though AddValues() takes one parameter, we passed in 4. The four numbers will automatically be converted into an array and passed in the values array.