Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a string array in a method call as a parameter in C#

If I have a method like this:

public void DoSomething(int Count, string[] Lines)
{
   //Do stuff here...
}

Why can't I call it like this?

DoSomething(10, {"One", "Two", "Three"});

What would be the correct (but hopefully not the long way)?

like image 603
Mr. Smith Avatar asked Sep 13 '09 00:09

Mr. Smith


3 Answers

you can do this :

DoSomething(10, new[] {"One", "Two", "Three"});

provided all the objects are of the same type you don't need to specify the type in the array definition

like image 165
Simon_Weaver Avatar answered Nov 01 '22 03:11

Simon_Weaver


If DoSomething is a function that you can modify, you can use the params keyword to pass in multiple arguments without creating an array. It will also accept arrays correctly, so there's no need to "deconstruct" an existing array.

class x
{
    public static void foo(params string[] ss)
    {
        foreach (string s in ss)
        {
            System.Console.WriteLine(s);
        }
    }

    public static void Main()
    {
        foo("a", "b", "c");
        string[] s = new string[] { "d", "e", "f" };
        foo(s);
    }
}

Output:

$ ./d.exe 
a
b
c
d
e
f
like image 10
Mark Rushakoff Avatar answered Nov 01 '22 02:11

Mark Rushakoff


Try this:

DoSomething(10, new string[] {"One", "Two", "Three"});
like image 2
Eran Betzalel Avatar answered Nov 01 '22 02:11

Eran Betzalel