Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is instantiating a Queue using {a,b,c} possible in C#?

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?

like image 625
xeophin Avatar asked Oct 26 '10 15:10

xeophin


2 Answers

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.

like image 65
digEmAll Avatar answered Oct 14 '22 09:10

digEmAll


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.

like image 36
Eric Lippert Avatar answered Oct 14 '22 10:10

Eric Lippert