0

I have written a simple program using the params keyword to take parameters and write them to the console. What I want/expect to happen, and what the C# documentation states will happen when I pass a single array to the parameter with the params tag is that the array will become the first element in the params array. Here is some sample code:

    public static void Main()
    {
        Paramtest(new object[] { "hi", "wow", 78 });
        Console.ReadKey();
    }

    public static void Paramtest(params object[] args) {
        foreach (object o in args) {
            Console.WriteLine("{0} is a type of {1}.", o.ToString(), o.GetType());
        }
    }

What I should see is one line of writing on the console that states:

System.object[] is a type of System.object[].

What I do see is three lines of writing:

hi is a type of System.String.
wow is a type of System.String.
78 is a type of System.Int32.

I've discovered that calling Paramtest with another parameter after the array, like this: Paramtest(new object[] { "hi", "wow", 78 }, String.Empty);, produces the intended results (plus the empty string), so that might be one way to work around this problem, however it isn't elegant or a good idea in my case. From what the documentation says, this shouldn't be happening. Is there any elegant workaround for this problem?

Douglas Dwyer
  • 562
  • 7
  • 14
  • 1
    Possible duplicate of [C# params apparent compiler bug (C# 5.0)](http://stackoverflow.com/questions/9709642/c-sharp-params-apparent-compiler-bug-c-5-0) – Raymond Chen Jul 31 '16 at 16:03
  • Yes, I think it is :( Unfortunately, I did not see that post when doing my research before posting my question. – Douglas Dwyer Jul 31 '16 at 16:07

2 Answers2

1

You can cast the argument to an object:

public static void Main()
{
    Paramtest((object)new object[] { "hi", "wow", 78 });
    Console.ReadKey();
}
Udo
  • 449
  • 3
  • 13
1

I agree that the sample code you pointed to in the documentation can lead to a bit of confusion. Here you are using Object array whereas the example used an Integer array, which is handled differently.

Look at this answer to understand whats going on: C# params object[] strange behavior

Community
  • 1
  • 1
sachin
  • 2,341
  • 12
  • 24