Out Parameters
In addition to passing values by reference, you can also specify that a given parameter is an out
parameter by using the out keyword, which is used in the same way as the ref keyword (as a modifier
to the parameter in the function definition and in the function call). In effect, this gives you almost
exactly the same behavior as a reference parameter in that the value of the parameter at the end of the
function execution is returned to the variable used in the function call. However, there are important
differences:
- Whereas it is illegal to use an unassigned variable as a ref parameter, you can use an
unassigned variable as an out parameter
- An out parameter must be treated as an unassigned value by the function that uses it.
This means that while it is permissible in calling code to use an assigned variable as an out parameter,
the value stored in this variable is lost when the function executes.
As an example, consider an extension to the MaxValue() function shown earlier, which returns the
maximum value of an array. Modify the function slightly so that you obtain the index of the element
with the maximum value within the array. To keep things simple, obtain just the index of the first
occurrence of this value when there are multiple elements with the maximum value. To do this, you add
an out parameter by modifying the function as follows:
static int MaxValue(int[] intArray, out int maxIndex)
{
int maxVal = intArray[0];
maxIndex = 0;
for (int i = 1; i < intArray.Length; i++)
{
if (intArray[i] > maxVal)
{
maxVal = intArray[i];
maxIndex = i;
}
}
return maxVal;
}
You might use this function as shown here:
int[] myArray = {1, 8, 3, 6, 2, 5, 9, 3, 0, 2};
int maxIndex;
Console.WriteLine(“The maximum value in myArray is {0}”,
MaxValue(myArray, out maxIndex));
Console.WriteLine(“The first occurrence of this value is at element {0}”,
maxIndex + 1);
This results in the following:
The maximum value in myArray is 9
The first occurrence of this value is at element 7
One has been added to the value of maxIndex returned here when it is displayed onscreen. This is to
translate the index to a more readable form, so that the first element in the array is referred to as element
1, rather than element 0.