18

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

5 Answers 5

34

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

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Could you explain why the new[] is required though? If I did: string[] MyString = {"One", "Two", "Three"}; it works just fine?
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"};
these articles are very useful. object initializers make code sooo much cleaner weblogs.asp.net/scottgu/archive/2007/03/08/… and for more on your original question see this msdn.microsoft.com/en-us/library/…
11

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

1 Comment

This is also a brilliant suggestion!
3

You can also create it using [ ], like this:

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

1 Comment

It should be noted that this is new Collection Expression syntax in C# 12+ and will not work for earlier versions.
2

Try this:

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

Comments

2

You can construct it while passing it in like so:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.