tags:

views:

76

answers:

4

If we have two procedures:

public void MyFirstParamsFunction(params object[] items)
{
    //do something
    MySecondParamsFunction(items, "test string", 31415)
}

public void MySecondParamsFunction(params object[] items)
{
    //do something
}

How will second procedure interpret the items from first? As sole objects, or as one object, that is object[]?

+5  A: 

object[] items will be interpreted as one object[] parameter.

Andrew Bezzub
+2  A: 

If you check it yourself you would have noticed that it is seen as a single object.

So in MySecondParamsFunction the items parameter will have length of 3 in this case.

astander
+2  A: 

The params keyword is just a bit of syntactic sugar.

Calling MyFirstParamsFunction(1, 2, 3) is the same as MyFirstParamsFunction(new object[] { 1, 2, 3 }). The compiler injects the code to create the array behind your back.

Tergiver
+2  A: 

This call:

MySecondParamsFunction(items, "test string", 31415); 

Will expand to this:

MySecondParamsFunction(new object[] { items, "test string", 31415 });

So you'll have 3 items in your params array for the call. Your original items array will be crammed into the first item in the new array.

If you want to just have a flattened parameter list going into the second method, you can append the new items to the old array using something like this:

MySecondParamsFunction(
  items.Concat(new object[] { "test string", 31415 }).ToArray());

Or maybe with a nicer extension method:

MySecondParamsFunction(items.Append("test string", 31415));

// ...

public static class ArrayExtensions {
  public static T[] Append<T>(this T[] self, params T[] items) {
    return self.Concat(items).ToArray();
  }
}
Jordão