Passing an array as an argument to params

I have the following method:

void MyMethod(params object[] args)
{
}

which I am trying to call with a type parameter object[]:

object[] myArgs = GetArgs();
MyMethod(myArgs);

It compiles fine, but inside MyMethodI args == { myArgs}, that is, an array with one element, which are my original arguments. Obviously, I wanted to have args = myArgswhat I'm doing wrong?

EDIT:
John Skeet was actually right, GetArgs()made a wrapper in an array of one element, sorry for the stupid question.

+4
source share
1 answer

What you described simply does not happen. The compiler does not create an array of wrappers if necessary. Here's a short but complete program that demonstrates this:

using System;

class Test
{
    static void MyMethod(params object[] args)
    {
        Console.WriteLine(args.Length);
    }

    static void Main()
    {
        object[] args = { "foo", "bar", "baz" };
        MyMethod(args);
    }
}

, 1 - , 3. args MyMethod .

, , "" GetArgs.

, args object. , Main :

MyMethod((object) args);

... 1, MyMethod(new object[] { args }).

+13

Source: https://habr.com/ru/post/1526367/


All Articles