Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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" });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top