C# Functions Part 5 Overloading


This entry is part 5 of 6 in the series C# Functions

Function Overloading and Out Parameters

You want a function that returns the maximum value from an array of values that you pass in. We want to call our function MaxValue(). Also, we want to use our MaxValue() function in cases where we pass in integers and doubles. We can do this. We do not need to two separate functions called IntMaxValue() and DoubleMaxValue().

Function overlaoding allows us to create multiple functions with the same name, each working with different parameter types.

The Function Signature includes the function name and its parameters (but not the return value). 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.

Her is some code.

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
        }
    }
}
Series Navigation<< C# Functions Part 4 Out ParameterC# Functions Part 6 Delegates >>