6

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?

xeophin
  • 123
  • 6

3 Answers3

18

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
  • 56,430
  • 9
  • 115
  • 140
  • Okay … would have been too convenient to be true ;) Thanks! – xeophin Oct 26 '10 at 15:23
  • Doesn't this method require unboxing the strings? Would `new List { "A", "B", "C" }` be better? – Robert Harvey Oct 26 '10 at 15:23
  • 5
    @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 Oct 26 '10 at 15:25
12

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
  • 647,829
  • 179
  • 1,238
  • 2,067
  • Thanks for that explanation, that helps a lot in understanding the underlying mechanics. – xeophin Oct 26 '10 at 15:36
  • So collection intializers are basically syntactic sugars, aren't they ? – digEmAll Oct 26 '10 at 15:37
  • 2
    @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 Oct 26 '10 at 15:58
  • oh you're right, I didn't think to the expression thing... thanks :) – digEmAll Oct 26 '10 at 16:11
3

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" });
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
vc 74
  • 37,131
  • 7
  • 73
  • 89