Home > Blockchain >  Calling a method that takes a variable parameter list with an array
Calling a method that takes a variable parameter list with an array

Time:01-09

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?

CodePudding user response:

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);

CodePudding user response:

try this method

public static object InvokeAsync(params object[] arguments)
{
  if (!arguments.GetType().Name.Contains("Object")) arguments = 
                                                     new object[] { arguments };
  return arguments;
}

test

var result1 =InvokeAsync(new string[] { "Test1","Test2"});
var result2 =InvokeAsync(new string[] { "Test1","Test2"},new string[] { "Test3","Test4"} );
var result3 =InvokeAsync(new string[] { "Test1","Test2"}, 3 );

result1

[
  [
    "Test1",
    "Test2"
  ]
]

result2

[
  [
    "Test1",
    "Test2"
  ],
  [
    "Test3",
    "Test4"
  ]
]

result 3

[
  [
    "Test1",
    "Test2"
  ],
  1
]
  •  Tags:  
  • Related