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?
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With