views:

254

answers:

4

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)?

+2  A: 

Try this:

DoSomething(10, new string[] {"One", "Two", "Three"});
Eran Betzalel
+11  A: 

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

Simon_Weaver
Perfect! Could you explain why the new[] is required though? If I did: string[] MyString = {"One", "Two", "Three"}; it works just fine?
Mr. Smith
its just the way the syntax works. you cant do this : var x = string[] {"One", "Two", "Three"}; but you can do this var y = new[] {"One", "Two", "Three"};
Simon_Weaver
these articles are very useful. object initializers make code sooo much cleaner http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx and for more on your original question see this http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx#cs3spec_topic7
Simon_Weaver
+2  A: 

You can construct it while passing it in like so:

DoSomething(10, new string[] { "One", "Two", "Three"});
Paul Williams
+7  A: 

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
Mark Rushakoff
This is also a brilliant suggestion!
Mr. Smith