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);
Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
They work the same way, and you can even pass the type parameter as a type parameter to another function.
Sadly, that's the answer. No, there is not. Not without converting it to an array (for example with .ToArray()
).
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With