For example I have C# method like this:
void someMethod(String arg1, params object[] extras)
{
foreach (object extra in extras)
{
Console.WriteLine(extra);
}
}
When I call it like this:
int[] vals = new int[] { 10, 25 };
someMethod("String", vals);
I get output:
System.Int32[]
Actually I wanted to pass vals variable as multiple int arguments, not as a single argument of array type, is there any way to do it?
2
There is no other way. The problem is that the extras
parameter is of type array (object []
), the params
is just syntactic sugar, which means you can’t really pass multiple parameters, just one, which can even be null
.
Overloading for params
methods specifies that it first tries to match the array parameter directly. Only then does it try to match by the params
element.
The reason it’s not working here is because an int[]
array is not an object[]
array, nor can it be casted to one.
It would work if you declared it
object[] vals = new object[] { 10, 25 };
Alternatively change the method
void someMethod(String arg1, params int[] extras)