Search code examples
c#arrayssyntaxvariadic-functionsparams-keyword

Unpacking an array into method arguments


As you know C# supports variadic methods through the params keyword:

int Add(params int[] xs) {
    return xs.Sum();
}

Which can then be called with any number of arguments you like:

Add(1);
Add(1, 2);
Add(1, 2, 3);

But say I want to call Add using an array of ints1. Is this possible and how (preferably without reflection)? I tried the following but they gave syntax errors (the syntax was pure guessing):

var xs = new[] { 1, 2, 3 };
Add(xs...); // doesn't work; syntax error
Add(params xs); // doesn't work; syntax error

1 My actual use-case is different but I thought this example would be less complicated.


Solution

  • Your method needs a return type:

    int Add(params int[] xs) {
        return xs.Sum();
    }
    

    And to call it with an array you just use the ordinary syntax for method calls:

    int[] xs = new[] { 1, 2, 3 };
    var result = Add(xs);