There is a collection in .Net used to manage values in a Stack
that uses the LIFO (last-in first-out) concept. The basics of stacks is the method Push(T item)
which is used to add elements in the stack and Pop()
which is used to get the last element added and remove it from the stack. The generic version can be used like the following code for a queue of strings.
First, add the namespace:
using System.Collections.Generic;
and use it:
Stack<string> stack = new Stack<string>();
stack.Push("John");
stack.Push("Paul");
stack.Push("George");
stack.Push("Ringo");
string value;
value = stack.Pop(); // return Ringo
value = stack.Pop(); // return George
value = stack.Pop(); // return Paul
value = stack.Pop(); // return John
There is a non generic version of the type, which works with objects.
The namespace is:
using System.Collections;
And a code sample of non generic stack:
Stack stack = new Stack();
stack.Push("Hello World"); // string
stack.Push(5); // int
stack.Push(1d); // double
stack.Push(true); // bool
stack.Push(new Product()); // Product object
object value;
value = stack.Pop(); // return Product (Product type)
value = stack.Pop(); // return true (bool)
value = stack.Pop(); // return 1d (double)
value = stack.Pop(); // return 5 (int)
value = stack.Pop(); // return Hello World (string)
There is also a method called Peek() which returns the last element added but without removing it from the Stack
.
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
var lastValueAdded = stack.Peek(); // 20
It is possible to iterate on the elements on the stack and it will respect the order of the stack (LIFO).
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.Push(50);
foreach (int element in stack)
{
Console.WriteLine(element);
}
The output (without removing):
50
40
30
20
10