Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a literal initialiser for Stack or Queue?

Tags:

c#-4.0

This:

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

fails with:

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

which does make me wonder why the compiler was dumb enough to ask for Add.

So, how should one initialise at a Queue/Stack constructor?

like image 783
ChrisJJ Avatar asked Sep 27 '11 15:09

ChrisJJ


1 Answers

Collection initializers are a compiler feature that call the Add method with each item you pass. If there is no Add method, you can't use it.

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

var stack = new Stack<int>(new [] { 1, 2, 3 });
like image 89
SLaks Avatar answered Oct 20 '22 23:10

SLaks