Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array as `params` argument

Tags:

c#

.net

params

I have the following method:

void MyMethod(params object[] args)
{
}

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

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

It compiles fine, but inside MyMethod I args == { myArgs}, i.e. an array with one element that is my original arguments. Obviously I wanted to have args = myArgs, what am I doing wrong?

EDIT:
Jon Skeet was actually right, the GetArgs() did wrap the thing in an one element array, sorry for stupid question.

like image 631
Grzenio Avatar asked Feb 11 '14 14:02

Grzenio


People also ask

Can we pass array in params?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

How do you pass an array of objects as an argument?

Passing array of objects as parameter in C++ It can be declared as an array of any datatype. Syntax: classname array_name [size];

Can you pass an array as a parameter in Javascript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.

Can an entire array be passed as a parameter Java?

You can pass an entire array, or a single element from an array, to a method. Notice that the int [ ] indicates an array parameter. Notice that passing a single array element is similar to passing any single value. Only the data stored in this single element is passed (not the entire array).


1 Answers

What you've described simply doesn't happen. The compiler does not create a wrapper array unless it needs to. Here's a short but complete program demonstrating 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);
    }
}

According to your question, this would print 1 - but it doesn't, it prints 3. The value of args is passed directly to MyMethod, with no further expansion.

Either your code isn't as you've posted it, or the "wrapping" occurs within GetArgs.

You can force it to wrap by casting args to object. For example, if I change the last line of Main to:

MyMethod((object) args);

... then it prints 1, because it's effectively calling MyMethod(new object[] { args }).

like image 60
Jon Skeet Avatar answered Nov 08 '22 14:11

Jon Skeet