2

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

1

2 Answers 2

3

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

string[] myArray = new[] { "param3", "param4" };
Foo(new[] { "param1", "param2" }.Concat(myArray).ToArray());
Sign up to request clarification or add additional context in comments.

1 Comment

Great option. Definitely the shortest idea I've seen so far
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);

2 Comments

Yeah, unfortunately there's a reason Foo is using params - there's no guaranteed "first" parameter and "second" parameter. It fluctuates between usecases
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.