0

For example, let's say we have a method

private void foo(int a, int b, int c)
{
    // do something...
}

and some sort of list containing some values

List<int> Numbers = new List<int> {
    8, 9, 10
};

My question is: Is it possible to pass the whole list as arguments for the declared method if it contains exactly the needed number of elements as the parameters, as in the example?

Something like ...

foo(Numbers);

foo(List<int> Numbers);
  • Have you tried the second one? – SᴇM Jun 28 '22 at 08:29
  • 1
    Yes. Try your second option, also look at the params keyword – Jonathan Twite Jun 28 '22 at 08:30
  • Nope, because the compiler doesn't know how many elements are in any given list, which might seem odd to you because *you* know there is 3 elements in there and there wont be anything other than those three elements, but the compiler can't/ doesn't assume that and there's no syntactic sugar to tell it just do that, you'll need/ want to do `Foo(Numbers[0], Numbers[1], Numbers[2])`, you can see it leads to a compile time error [here](https://dotnetfiddle.net/6ErVBc) – MindSwipe Jun 28 '22 at 08:32
  • @MindSwipe if you remove the `foo(List Numbers);` in your example and place it in the method below, like `private static void Foo(List numbers)`, then it will compile correctly. It will also carry over the list with it's contents. Perhaps not the same as passing over it's contents as arguments, but it can archieve the same effect – Steven Jun 28 '22 at 09:07

0 Answers0