views:

114

answers:

3

Is it possible to do that in C#?

Queue<string> helperStrings = {"right", "left", "up", "down"};

or do I have to produce an array first for that?

+7  A: 

No you cannot initialize a queue in that way.

Anyway, you can do something like this:

var q = new Queue<string>( new[]{ "A", "B", "C" });

and this, obviously, means to pass through an array.

digEmAll
+1 Yes, you create an array first, but it looks pretty :)
Onkelborg
Okay … would have been too convenient to be true ;) Thanks!
xeophin
Doesn't this method require unboxing the strings? Would `new List<string> { "A", "B", "C" }` be better?
Robert Harvey
@Robert Harvey: First, strings are reference types. Only value types are boxed. Second, even if the array were of value type, the implicitly typed array creation operator infers the type. new[] { 1, 2, 3} is an array of unboxed ints, not an array of boxed ints!
Eric Lippert
@Eric: Got it, thanks!
Robert Harvey
+3  A: 

As Queue<T> does not implement an 'Add' method, you'll need to instantiate an IEnumerable<string> from which it can be initialized:

Queue<string> helperStrings 
    = new Queue<string>(new List<string>() { "right", "left", "up", "down" });
vc 74
+9  A: 

Is it possible to do that in C#?

Unfortunately no.

The rule for collection initializers in C# is that the object must (1) implement IEnumerable, and (2) have an Add method. The collection initializer

new C(q) { r, s, t }

is rewritten as

temp = new C(q);
temp.Add(r);
temp.Add(s);
temp.Add(t);

and then results in whatever is in temp.

Queue<T> implements IEnumerable but it does not have an Add method; it has an Enqueue method.

Eric Lippert
Thanks for that explanation, that helps a lot in understanding the underlying mechanics.
xeophin
So collection intializers are basically syntactic sugars, aren't they ?
digEmAll
@digEmAll: that is correct. The sweetness of the sugar here is twofold. First, that they are very compact. Second, that they turn what would have previously been a bunch of statements into an expression; that means you can use these in contexts where only an expression is valid, such as a field initializer or LINQ query.
Eric Lippert
@Eric: oh you're right, I didn't think to the expression thing... thanks :)
digEmAll