Unpacking an array into method arguments

user142019 picture user142019 · Feb 20, 2013 · Viewed 7.3k times · Source

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.

Answer

Mark Byers picture Mark Byers · Feb 20, 2013

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