O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Queue<T> and Stack<T>

To conclude our journey through the generic collection types, we meet again with the queue and stack collections in a generic shape. Because their use is completely analogous to the nongeneric counterparts, we just go for a translation of the original example, now with stronger type checking at compile time and making ugly casts go away:

var postOffice = new Queue<Person>();postOffice.Enqueue(new Person("Bart", 10));postOffice.Enqueue(new Person("Homer", 38));postOffice.Enqueue(new Person("Ned", 60));var bart = postOffice.Dequeue();var homer = postOffice.Peek(); // D'ohint twoLeft = postOffice.Count;

And for a stack

var stack = new Stack<int>();stack.Push(1);stack.Push(2);stack.Push(3);var three ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required