Collections
C# includes various classes that store the values or objects called collections.
There are two types of collections available in C#
Non-generic collections and Generic collections
The System. The collections namespace contains the non-generic collection types and systems.Collections.Generic namespace includes generic collection types.
In most cases, it is recommended to use the generic collections because they perform faster than non-generic collections and also minimize exceptions by giving compile-time errors.
Non-generic Collections ArrayList, Stack, Queue, Hashtable.
Stack
Stack is a special type of collection that stores elements in LIFO style (Last In, First Out). C# includes the generic Stack<T> and non-generic Stack collection classes.
Stack is useful to store temporary data in LIFO style, and you might want to delete an element after retrieving its value.
Creating a Stack
Example
Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
foreach (var item in myStack)
Console.Write(item + ","); //prints 4,3,2,1,
Pop()
The Pop() method returns the last element and removes it from a stack. If a stack is empty, then it will throw the InvalidOperationException. So, always check for the number of elements in a stack before calling the Pop() method.
Example
Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
Console.Write("Number of elements in Stack: {0}", myStack.Count);
while (myStack.Count > 0)
Console.Write(myStack.Pop() + ",");
Console.Write("Number of elements in Stack: {0}", myStack.Count);
Peek()
The Peek() method returns the last added value from the stack but does not remove it. Calling the Peek() method on an empty stack will throw the InvalidOperationException. So, always check for elements in the stack before retrieving elements using the Peek() method.
Example
Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
Console.Write("Number of elements in Stack: {0}", myStack.Count); // prints 4
if (myStack.Count > 0)
{
Console.WriteLine(myStack.Peek()); // prints 4
Console.WriteLine(myStack.Peek()); // prints 4
}
Console.Write("Number of elements in Stack: {0}", myStack.Count); // prints
Contains()
The Contains() method checks whether the specified element exists in a Stack collection or not. It returns true if it exists; otherwise, it is false.
Example
Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
myStack.Contains(2); // returns true
myStack.Contains(10); // returns false
Happy Coding!
Thanks