C# Functions Part 4


You can pass values by reference. Also you can specify that a given parameter is an out parameter by specifying the out keyword just like you would use the ref keyword. Use the out keyword in the function definition and in the function call. The value of the parameter at the end of the execution is returned to the variable used in the function call, just like passing by reference.

It is illegal to use an unassigned variable as a ref parameter you can use an unassigned variable as an out parameter.

An out paramter 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.

Here is an example of a functions with an out parameter. This function gives you the index of the first occurrence of this value when there are multiple elements with the same maximum value.

class Program  {  // Functions - Out Parameters 
    static void Main(string[] args)   {
        int[] myArray = { 3, 8, 4, 9 };
        int MaxIndex;  // You can use an unassigned variable as an out parameter
        // but you cannot use an unassigned variable as a reference parameter.
        // The line below returns one value, namely maxVal and
        // it also sets the value of MaxIndex above (an out parameter).
        WriteLine($"The maximum value in myArray is {MaxValueInArray(myArray, out MaxIndex)}");
        WriteLine($"The first occurrance of the value is at element {MaxIndex + 1}");
        ReadKey();
    }
    static int MaxValueInArray(int[] intArray, out int maxIndex)  {
        int maxVal = intArray[0];  // the first one
        maxIndex = 0;
        for (int i = 1; i < intArray.Length; i++)  {
            if (intArray[i] > maxVal)  {
                maxVal = intArray[i];
                maxIndex = i;  
	      }
        return maxVal;  // the first WriteLine() line in Main() returns maxVal
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *