C# Functions Part 5


Function Overloading and Out Parameters

Function Signature—includes the function name and its parameters. Also, using ref in the parameters changes the signature. The return value is not part of the function signature. You can have the same function name, such as MaxValueInArray, and have different parameters. It would be an error to define two functions with the same signature. That is ambiguous.

namespace OutParameters
{
    class Program  {  // Out Parameters & Function Overloading
        static void Main(string[] args)   {
            int[] myArray = { 3, 8, 4, 9 };
            int MaxIndex;  // See previous example 
            WriteLine($"The maximum value in myArray is {MaxValueInArray(myArray, out MaxIndex)}");
            WriteLine($"The first occurrance of the value is at element {MaxIndex + 1}");
            double[] myDArray = { 3.5d, 8.3d, 4.7d, 2.1d };
            WriteLine($"The maximum value in myDArray is {MaxValueInArray(myDArray, 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 above returns maxVal
        }
        static double MaxValueInArray(double[] doubleArray, out int maxIndex) {
            double maxVal = doubleArray[0];  // the second one
            maxIndex = 0;
            for (int i = 1; i < doubleArray.Length; i++)  {
                if (doubleArray[i] > maxVal)  {
                    maxVal = doubleArray[i];
                    maxIndex = i; }
            }
            return maxVal;  // the first WriteLine() line above returns maxVal
        }
    }
}

Leave a comment

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