0

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
  • That cannot be right... the only way you'd ge this output is you were outputting the extras parameter, not its individual values! Commented Aug 8, 2024 at 13:08
  • 1
    Can't you just call it like: someMethod("String", 10, 25); ? Commented Aug 8, 2024 at 13:10

3 Answers 3

8

Overload resolution 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)

Or you can cast it using Linq etc

someMethod("String", vals.Cast<object>().ToArray());
Sign up to request clarification or add additional context in comments.

Comments

4

You can make a generic "overload-like" method next to the regular method:

void someMethod(String arg1, params object[] extras) {
    foreach (object extra in extras) {
        Console.WriteLine(extra);
    }
}

void someMethod<T>(String arg1, params T[] extras) {
    foreach (T extra in extras) {
        Console.WriteLine(extra);
    }
}

The compiler will pick up this method and infer the type and you would use it easily, but it can fallback to the object version too.

int[] vals = new int[] { 10, 25 };
someMethod("String", vals);

// 10,25
someMethod("String",1,3,"foo");
// 1, 3 "foo"

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.