Output options
In addition to passing values ββby reference, you can also indicate that this parameter is out 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 function call). In essence, this gives you almost exactly the same behavior as the reference parameter, in that the parameter value at the end of the function execution is returned to the variable used in the function call. However, there are important differences:
- While it is illegal to use an unrecognized variable as the ref parameter, you can use an unrecognized variable as the out parameter
- The out parameter should be considered as an unassigned value by the function that uses it.
This means that although the assigned variable is used as the out parameter in the code call, the value stored in this variable is lost when the function is executed.
As an example, consider the extension of the MaxValue () function shown earlier, which returns the maximum value of an array. Change the function a bit to get the index of the element with the maximum value inside the array. To keep things simple, get only the index of the first occurrence of this value in the presence of several elements with a maximum value. To do this, add the out parameter by changing 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 can use this function as shown below:
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 in the element {0}", maxIndex + 1);
The result is the following:
The maximum value in myArray is 9
The first occurrence of this value is in element 7
One is added to the maxIndex value returned here when it is displayed on the screen. This is to translate the index into a more readable form, so the first element in the array is called element 1, not element 0.