C# reference parameters
Reference parameters allows a method to change the values of data that are defined in the caller's scope. In other languages, the traditional approach to achieving this would be to modify global variables or return some value and have the caller assign this to whatever it wants.
Toy example
Note here that i
is a reference parameter and that we have to use the ref
modifier to signal that. What happens when we call AddHundred
?
We're printing the value of numberOfPaperClips
before and after the method call to verify that the value of numberOfPaperClips
does indeed change, despite the variable being outside the scope of AddHundred()
. (The Console.ReadLine()
call is just to prevent the console application from terminating immediately.
And the output:
Output vs reference parameters
- Output parameters have to be assigned before the method they are declared in ends. However, they do not need to be initialised before they are passed into the method that takes them as parameters
- Since reference parameters allow you to modify the value of some data, you have to initialise the reference parameter before you pass it into a method. You are not able to modify (e.g. increment an integer) if it is unassigned.