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.

1class Program  // Functions - params keyword
2{
3    static int SumIntVals(ref string myStr, params int[] vals)
4    // params must be last in the list
5        myStr = "Hello " + myStr;
6        int sum = 0;
7        foreach (int val in vals)
8        // they must all be int type
9            sum += val;
10        }
11        // can pass in no integers if you want
12        return sum;
13    }
14    static void Main(string[] args)
15    {
16        int myInt = 2;
17        string strMe = "Mike";
18        int sum = SumIntVals(ref strMe, 1, myInt, 5, 3);
19        // must use ref otherwise Hello will not
20        // be concatenated to the strMe variable!
21        Console.WriteLine("{0}, your summed values = {1}", strMe, sum);
22 
23        // passing in the integers is optional
24        int sum2 = SumIntVals(ref strMe);
25        Console.WriteLine({0}, your summed values = {1}", strMe, sum2);
26 
27        Console.WriteLine("Press any key to continue...");
28        Console.ReadKey();
29 
30    }
31}

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 >>