LIFO data collection in .NET: Stack of T
January 7, 2014 Leave a comment
If you need a data collection in .NET where you are forced to handle the objects in a last-in-first-out manner then you can use the Stack of T object: the last object added will be the first to come out. A typical scenario is a deck of cards: you pick the first card from the top, i.e. the one that was added last.
To initialise:
Stack<Card> stackOfCards = new Stack<Card>();
To add items:
stackOfCards.Push(new Card(ace)); stackOfCards.Push(new Card(ten));
To get the most recently added object from the stack:
Card next = stackOfCards.Pop();
The Pop() method will also remove the item from the collection. So the next time you call Pop() you’ll get the item added before the most recently added one.
Just like with a Queue of T you cannot directly reference an object in the stack collection by some index, e.g. [3].
The Peek() method will let you view the next item on the stack but it won’t be removed from the collection:
Card next = stackOfCards.Peek();
You can test for the absence of an item with Contains:
bool contains = stackOfCards.Contains(ace);
If you absolutely need to access the items directly then convert the stack into an array:
Card[] cardArray = stackOfCards.AsArray();
This will copy the items in the stack but leave the stack itself intact.