xeophin
xeophin

Reputation: 123

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?

Upvotes: 6

Views: 2460

Answers (4)

Mr. Squirrel.Downy
Mr. Squirrel.Downy

Reputation: 1177

The exact answer is: yes.
As Eric Lippert said, it is actually the syntactic sugars, is the syntax analysis of the compiler, so it means that if the compiler can be made aware that Queue has an Add method, then it can "fool the compiler".
"Extension method" can made it:

public static class QueueHacky
{
    public static void Add<T>(this Queue<T> queue, T newItem)
    {
        queue.Enqueue(newItem);
    }
}

Then, this becomes legal:

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

Warning: This is a Hacky solution, it just for solved this question, not recommend to use, it has code smell.

Upvotes: 0

vc 74
vc 74

Reputation: 38179

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" });

Upvotes: 3

Eric Lippert
Eric Lippert

Reputation: 660148

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.

Upvotes: 12

digEmAll
digEmAll

Reputation: 57210

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.

Upvotes: 18

Related Questions