87

Is there a way to set up a C# function to accept any number of parameters? For example, could you set up a function such that the following all work -

x = AddUp(2, 3)

x = AddUp(5, 7, 8, 2)

x = AddUp(43, 545, 23, 656, 23, 64, 234, 44)
Svetlozar Angelov
  • 21,214
  • 6
  • 62
  • 67
Craig Schwarze
  • 11,367
  • 15
  • 60
  • 80

3 Answers3

185

Use a parameter array with the params modifier:

public static int AddUp(params int[] values)
{
    int sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum;
}

If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:

public static int AddUp(int firstValue, params int[] values)

(Set sum to firstValue to start with in the implementation.)

Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:

int x = AddUp(4, 5, 6);

into something like:

int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);

You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.

Syntax Error
  • 1,600
  • 1
  • 26
  • 60
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • In `public static int AddUp(params int[] values)` the `values` will always be of type `T[]`? Can it not be of type `params IEnumerable values` or `params List values`. I tried using `params IEnumerable values` but it gave me error, which was later resolved using `params IEnumerable[] values`. Why so? – phougatv Jun 22 '17 at 10:19
  • 1
    @barnes: `params` only works for array types (at the moment; there have been proposals to allow other types). You almost certainly *don't* want `params IEnumerable[]` as that would be an array of sequences. – Jon Skeet Jun 22 '17 at 10:20
7

C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Tarydon
  • 5,097
  • 23
  • 24
4

1.You can make overload functions.

SomeF(strin s){}   
SomeF(string s, string s2){}    
SomeF(string s1, string s2, string s3){}   

More info: http://csharpindepth.com/Articles/General/Overloading.aspx

2.or you may create one function with params

SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like

More info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

3.or you can use simple array

Main(string[] args){}
Pit J
  • 169
  • 8
  • 3
    Overloading in example 1 presented here is unnecessary, since that function can be written as : SomeF(string s, string s2 = "", string s3 = ""){ } – Volkan May 07 '19 at 10:28