C# reference parameters

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

private static void AddHundred(ref int i)
{
	i += 100;
}
Figure 1: a method that takes a reference parameter

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?

static void Main(string[] args)
{
	int numberOfPaperClips = 5;
	Console.WriteLine("Paper clips before: {0}", numberOfPaperClips);
	AddHundred(ref numberOfPaperClips);
	Console.WriteLine("Paper clips after: {0}", numberOfPaperClips);

	Console.ReadLine();
}
Figure 2: Calling a method that takes a reference parameter

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:

Paper clips before: 5
Paper clips after: 105
Figure 3: 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.