serious6
serious6

Reputation: 307

Pass a List to a params parameter

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

Upvotes: 17

Views: 17068

Answers (3)

Jecoms
Jecoms

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

Tim
Tim

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

nvoigt
nvoigt

Reputation: 77285

No

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

Upvotes: 18

Related Questions