C# Functions Part 2 Parameters


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

A parameter is part of the function definition, whereas an argument is passed to a function by calling code. When a function needs to accept parameters, you must specify the following:

  • A list of parameters accepted by the function in its definition, along with the types of those parameters.
  • A matching list of arguments in each function call.

The parameters are separated by a comma and each of the parameters are accessible from within the function. When you call a function you must supply arguments that match the function definition. This means that the following must match: the parameter types, the number of parameters and the order of parameters.

class Program  // Function Parameters
{ 
//
    // pass in an integer array and return an integer
    static int MaxValue(int[] intArray)
    {
        int maxVal = intArray[0];
        for (int i = 1; i < intArray.Length; i++)
        {
            if (intArray[i] > maxVal) maxVal = intArray[i];
        }
        return maxVal;  // must have return statement when not void
    }
    static void MySorting(ref int[] intputArray)
    {   // just for illustration purposes
        // don't need to write your own function 
        Array.Sort(intputArray);
    }
    static void Main(string[] args)
    {
        int[] myArray = { 1, 8, 3, 6, 9 };
        int maxVal = MaxValue(myArray);
        WriteLine(maxVal);
        MySorting(ref myArray);  // ref - the default is reference
        foreach (int i in myArray) Console.Write(i + " ");
        ReadKey();
    }
}

Functions Part 3

Series Navigation<< C# Functions IntroductionC# Functions Part 3 Params >>