C# Functions Part 3 Params


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

A paramter array is a special parameter for a function. You may pass one and only one parameter array to a function provided that it is the last parameter in the function. Now you can use a function by calling it with a variable number of parameters. The variable number of arguments that you pass must be of the same type. You create a parameter array with the params keyword.

Below is an example of the params keyword used in a C# function. We are passing in 4 integers to the function. The function can iterate through the array of integers with a foreach loop.

Here is some sample code.

class Program  // Functions - params keyword
{
    static int SumIntVals(ref string myStr, params int[] vals)
    {  // params must be last in the list
        myStr = "Hello " + myStr;
        int sum = 0;
        foreach (int val in vals)
        {  // they must all be int type
            sum += val;
        }
        // can pass in no integers if you want
        return sum;
    }
    static void Main(string[] args)
    {
        int myInt = 2;
        string strMe = "Mike";
        int sum = SumIntVals(ref strMe, 1, myInt, 5, 3);
        // must use ref otherwise Hello will not
        // be concatenated to the strMe variable!
        Console.WriteLine("{0}, your summed values = {1}", strMe, sum);

        // passing in the integers is optional
        int sum2 = SumIntVals(ref strMe);
        Console.WriteLine({0}, your summed values = {1}", strMe, sum2);

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();

    }
}

What does the output look like?

Notice that the second line of output has two “Hello”s. Why? Also, why is our function static?

Series Navigation<< C# Functions Part 2 ParametersC# Functions Part 4 Out Parameter >>