Search code examples
c#parameter-passingvariadic-functions

Calling a method that takes a variable parameter list with an array


Consider this method:

public static void InvokeAsync(params object[] arguments)
{
    // do something
}

Now I want to call it with a single argument of type string[]:

InvokeAsync(new string[] { "Test" });

unfortunately, that results in arguments becoming the string[] instance and arguments[1] == "Test". I need the string array to be the first element of the object[] array.

I can work around this by using:

InvokeAsync(new object[] { new string[] { "Test" }});

but this defeats a bit the purpose of a params declaration and is also not nice (and not obvious!). Is there a better way?


Solution

  • It is the correct way. Arrays are covariant in C# so implicit conversion from string[] to object[] exists (which is actually not type safe, see the linked doc) and is used by compiler to treat your new string[] { "Test" } as arguments array. So you need to "explain" to the compiler what you actually want with this workaround.

    If you will actually have multiple parameters everything will work as expected:

    InvokeAsync(new string[] { "Test" }, 1);