2

I have a method

public void method(params object[][] arg)

But where I call the method, I have and object[] and object[][]:

object[] var1 = new object[5];
object[][] var2 = new object[8][5];
method(var1, var2); (I´d like this to be method(var1, var2[0], var2[1], var2[2],...)

But inside method, arg has length 2:

arg[0] = var1
arg[1] = var2

But I want arg as an array of length 9:

arg[0] = var1
arg[1] = var2[0];
arg[2] = var2[1];
... 

How can I call the method?

2 Answers 2

4

It sounds like you want:

object[][] args = new[] { var1 }.Concat(var2).ToArray();
method(args);

The "normal" parameter array handling of C# doesn't do any flattening: you either call it with a single argument which is already the right type, or you call it with a sequence of arguments of the element type. You can't mix and match.

Sign up to request clarification or add additional context in comments.

Comments

2

In general, for methods that accept a params array I also provide an overload that accepts IEnumerable<T>:

public void MyMethod(params string[] args)
{
    MyMethod((IEnumerable<string>)args);
}

public void MyMethod(IEnumerable<string> args)
{
    // ...
}

Then you can also easily provide an enumerable as the parameter. For example:

string[] var1 = new string[5];
string[][] var2 = new string[8][5];

// Jon Skeet's suggestion without ToArray():
var sequence = new[] { var1 }.Concat(var2);
MyMethod(sequence);

If you really want to use the syntax you propose, you can do that since in your example you use object[]. An array of objects is also an object, therefore you can do the flattening inside your method:

public void MyMethod(params object[] args)
{
    object[] flattened = arg
        // For each element that is not in an array, put it in an array.
        .Select(a => a is object[] ? (object[])a : new object[] { a })
        // Select each element from each array.
        .SelectMany(a => a)
        // Make the resulting sequence into an array.
        .ToArray();
    // ...
}

MyMethod(var1, var2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.