views:

112

answers:

2

If I have a function

void Foo(params int[] bar){}

The following runs fine:

int[] a1 = {1, 2, 3};
int[] a2 = {4, 5, 6};
Foo(1, 2, 3);
Foo(a1);

But these give compile errors:

Foo(a1, 1, 2, 3);
Foo(1, 2, a1);
Foo(1, a1, 2);
Foo(a1, a2, 1, 2, 3);

because only the first argument is allowed to be an int[], the rest have to be ints.

The final example is what I would like to do, but the language won't let me without combining the arrays first. I really like the simplicity of the syntax, and I would rather not add to the code more than I have to. Does anyone have a nice way to do this?

+11  A: 

It's weird. Foo(a1, 2, 3) shouldn't work. You should either pass an array or a bunch of integers. You can't mix them AFAIK. Do you have another overload or something?

There's not really a neat syntax for doing that. The most concise one I can think of is:

Foo(a1.Concat(a2).Concat(new[] {1,2,3}).ToArray());
Mehrdad Afshari
I agree `Foo(a1, 2, 3)` cannot work without another overload.
leppie
+1  A: 

Agreed, its very odd Foo(a1, 2, 3) works.

Heres an extension method for .Concat to make Mehrdad's syntax a little easier on the eyes.

public T[] Concat<T>(this T[] first, params T[] other)
    {
        T[] output = new T[first.Length+other.Length];

        first.CopyTo(output,0);
        other.CopyTo(output,first.Length);
        return output;
    }

Can be used as follows:

Foo(a1.Concat(a2).Concat(1,2,3));
Rich Oliver
Note that `Enumerable.Concat` is evaluated lazily while yours does the copy on each call. It can be inefficient if the number of `Concat` calls grows.
Mehrdad Afshari
Very good point.
Rich Oliver