Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# expand array to be arguments

void foo(int one, int two) {
}

public static void Main(string[] args) {
  var bar = new int[] { 1, 2 };
  foo(params bar);
}

What’s the correct syntax to deconstruct the bar array and pass it as the arguments to the foo method?

In some other languages you can use a splat operator foo(...bar) or an unpack operator foo(*bar).

How can I do it in C#?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There isn’t an equivalent function in C#. Each argument has to be passed individually.

There are, of course, work arounds that you likely already know. You could declare an overload for your function that would accept an array and call the original function using the first two inputs. The other alternative that I can think of is to declare the function parameter with the params keyword so that it could receive an array or multiple conma-separated elements when called.

void foo(params int[] numbers)
{   // TODO: Validate numbers length
    int one = numbers[0];
    int two = numbers[1];
}
public static void Main(string[] args) {
    var bar = new int[] { 1, 2 };
    // both valid function calls below
    foo(bar);
    foo(bar[0], bar[1]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading