Reputation: 307
Is there was a way to pass a List
as an argument to a params
parameter? Suppose I have a method like this:
void Foo(params int[] numbers)
{
// ...
}
This way I can call it by passing either an array of int
s or int
s separated by commas:
int[] numbers = new int[] { 1, 5, 3 };
Foo(numbers);
Foo(1, 5, 3);
I wanted to know if there is a way to also be able to pass a List
as an argument (without having to convert it to an array). For example:
List<int> numbersList = new List<int>(numbers);
// This won't compile:
Foo(numbersList);
Upvotes: 17
Views: 17068
Reputation: 2838
If able to change the existing code, you could always create an overload that accepts a List and passes it to the params method.
void Foo(params int[] numbers)
{
// ...
}
void Foo(IList<int> numbers) => Foo(numbers.ToArray());
Upvotes: 4
Reputation: 6060
You would want to change Foo
to accept something other than params int[]
to do this.
void Foo(IEnumerable<int> numbers) {
}
This would allow you to pass in either an int[]
or a List<int>
To allow both ways, you could do this:
void Foo(params int[] numbers) {
Foo((IEnumerable<int>)numbers);
}
void Foo(IEnumerable<int> numbers) {
//Do the real thing here
}
Upvotes: 5
Reputation: 77285
Sadly, that's the answer. No, there is not. Not without converting it to an array (for example with .ToArray()
).
Upvotes: 18