How to specify a literal initializer for a stack or queue?

It:

List<string> set = new List<string>() { "a","b" }; 

works fine, but:

 Stack<string> set = new Stack<string>() { "a","b" }; Queue<string> set = new Queue<string>() { "a","b" }; 

failure:

 ...does not contain a definition for 'Add' 

which makes me wonder why the compiler was stupid enough to ask Add.

So how to initialize in the Queue / Stack constructor?

+7
source share
1 answer

Collection initializers are a compiler function that calls the Add method with each element passed. If there is no Add method, you cannot use it.

Instead, you can call the Stack or Queue constructor, which takes an IEnumerable<T> :

 var stack = new Stack<int>(new [] { 1, 2, 3 }); 
+11
source

All Articles