This tutorial is about stacks in C#. The Stack class represents a last-in-first-out (LIFO) Stack of Objects
Don't forget to check out our site http://howtech.tv/ for more free how-to videos!
http://youtube.com/ithowtovids - our feed
http://www.facebook.com/howtechtv - join us on facebook
https://plus.google.com/103440382717658277879 - our group in Google+
Introduction
Stacks in C# represent a last-in-first-out (LIFO) Stack of Objects. A stack in C# will follow the push-pop operation. That is we can Push (insert) Items into Stack and Pop (retrieve) it back.
A stack in C# is implemented as a circular buffer. That is you can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is dynamically increased as required.
This is present in the namespace, System.Collections.
Step 1: Implementing Stack
The following code snippet shows the use of push and pop methods for stacks in C#:
Stack stack = new Stack();
stack.Push("one");
stack.Push("two");
stack.Push("three");
string s = Convert.ToString(stack.Pop());
foreach (string i in stack)
{
Console.Write("\t" + i);
}
Step 2: Manipulating Stack
The pop() method pushes the last element out. Note that the stack holds objects, just like ArrayList.
The elements of the stack can be iterated using the foreach statement as well.
There are few more methods and properties that can be functionally helpful:
• Peek() -- looks into the next element in the stack.
• Clear() -- deletes all the elements in stack.
• Count -- counts the number of elements in the stack.
Conclusion
Peek is similar to pop, However, peek does not remove the element from the stack while pop removes the reference entirely. Hence, if you call Pop and then Peek(), Peek() will return the next value in the stack since the reference of the first value is removed by Pop().
You can copy and search the elements of a stack, just like an ArrayList.