Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a List to a params parameter

Tags:

c#

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 ints or ints 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);
like image 922
serious6 Avatar asked Feb 28 '17 17:02

serious6


People also ask

What is parameter list in C#?

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.

What does the params keyword do when used in a method parameter list?

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.

Can you pass a type as a parameter?

They work the same way, and you can even pass the type parameter as a type parameter to another function.


2 Answers

No

Sadly, that's the answer. No, there is not. Not without converting it to an array (for example with .ToArray()).

like image 145
nvoigt Avatar answered Sep 21 '22 06:09

nvoigt


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
}
like image 39
Tim Avatar answered Sep 19 '22 06:09

Tim