Classes

Parameters

Reference Parameters

When passed as reference parameters, any change made to them will have effect. For example, if a int field is passed as a reference method, and inside the method receives a different value from the original, it really will have the value assigned by the method.

Because coding is the best way for learning, let's try to modify the Swap method to receive the parameters as reference parameters; actually, the only change is the reverved keyword ref before the type of the argument.

 //
 // parameters-value.cs
 // A second implementation of the Swap method
 //

using System;
 
 public class Tester {

 	// Interchange the values of a and b
	// Pay attention on the ref keyword
 	public void Swap ( ref int a, ref int b )
 	{

		int temp = a;
		a = b;
		b = a;
	
	}

	public static void Main ()
	{

		Tester t = new Tester();
		int a = 56;
		int b = 45;

		Console.WriteLine("a = {0} | b = {1}", a, b);
		t.Swap(ref a, ref b);
		Console.WriteLine("After Swap()");
		Console.WriteLine("a = {0} | b = {1}", a, b);

	}
		
		

 }
Note that the ref keyword -refering to by reference- is used both when declaring the method and when calling it.

Now save, compile and run it. You should get this:

a = 56 | b = 45
After Swap()
a = 45 | b = 45
Now their values were interchanged. Because the ref keyword, the parameters are passed as references, and the method works with their values directly.