0

If I have a method like this:

Foo(params string[] parameters)

I would like to pass in both "regular parameters" and an array in a single call like this:

string[] myArray = new[] { "param3", "param4" };
Foo("param1", "param2", myArray);

such that it is equivalent to this:

Foo("param1", "param2", "param3", "param4");

Is there a function I can call on the array or some sort of way that I can modify my Foo method? Currently I'm doing something like this:

string[] myArray = new[] { "param3", "param4" };
List<string> arguments = new List<string>
{
  "param1",
  "param2"
};
arguments.AddRange(myArray);
Foo(arguments.ToArray());

but I'm wondering if there's a better way

derekantrican
  • 1,891
  • 3
  • 27
  • 57
  • You're doing it the right way. There are other ways of concatenating arrays [How do I concatenate two arrays in C#?](https://stackoverflow.com/q/1547252/215552) Are they "better"? Depends on your definition. – Heretic Monkey Feb 18 '20 at 18:32

2 Answers2

2

If by "regular" parameters you mean separately defined arguments with names, and you want them to be optional, then we can define them with default values. Then we can define the last one as a params array (which may also be null or empty):

public static void Foo(string first = null, string second = null, params string[] others)

Now we can call the method as you described (the first two arguments are optional, followed by zero-to-many string arguments in the params array):

Foo();
Foo("param1");
Foo("param1", "param2");
Foo("param1", "param2", "param3");
Foo("param1", "param2", "param3", "param4");  // etc...

// Or call it with two regular arguments and an array
var myArray = new[] {"param3", "param4"};
Foo("param1", "param2", myArray); 

The one thing we can't do in this case is pass in just an array, or just one of the strings and an array, unless we used the named argument syntax:

Foo("param1", others:myArray); // Don't have to name the first one if we place it first
Foo(second:"param2", others:myArray);
Foo(others:myArray);
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • Yeah, unfortunately there's a reason `Foo` is using `params` - there's no guaranteed "first" parameter and "second" parameter. It fluctuates between usecases – derekantrican Feb 18 '20 at 18:38
  • Ok, then we can make the two named arguments optional by assigning them a default value. Is that what you're looking for? I've updated the question with a sample. – Rufus L Feb 18 '20 at 18:52
2

One concise way to pass all your paramters would look like this:

string[] myArray = new[] { "param3", "param4" };
Foo(new[] { "param1", "param2" }.Concat(myArray).ToArray());
JSteward
  • 6,833
  • 2
  • 21
  • 30