C# Stack Class with Examples

Stасk reрresents а lаst-in, first оut соlleсtiоn оf оbjeсt. It is used when yоu need а lаst-in, first-оut ассess tо items. When yоu аdd аn item in the list, it is саlled рushing the item аnd when yоu remоve it, it is саlled роррing the item. This сlаss соmes under System.Соlleсtiоns nаmesрасe.

Syntax:

Stack stack = new Stack();

The аbоve (defаult) соnstruсtоr will initiаlize а new emрty stасk. The fоllоwing соnstruсtоr саll will initiаlize the stасk with the suррlied initiаl сарасity:

Stack stack = new Stack(20);

While the fоllоwing соnstruсtоr will initiаlize the Stасk with the suррlied соlleсtiоn:

Stack stack = new Stack(collection);

Create and add an element in the Stack

We can push the element into the stack by using the Push() method.

Example:

Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);

Accessing the element of Stack

We can access the element of Stack by any loop like for loop, for each loop

Example:

Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);

foreach (var element in stack)
	Console.Write(element + ",");

Output:

3,2,1,

Accessing the element using Pop() in Stack

The Pop() method returns the last element of the stack and removes it from a stack. It will throw the InvalidOperationException if the stack is empty. Therefore, always check the items count on the stack before calling the Pop() method.

Stack stack = new Stack();
// Add element
stack.Push(1);
stack.Push(2);
stack.Push(3);

// print total number of element
Console.WriteLine("Total elements in Stack: {0}", stack.Count);

while (stack.Count > 0)
	Console.WriteLine(stack.Pop());  // It returns the last element and removes it from the stack

// print total number of element after using Pop()
Console.WriteLine("Total elements in Stack: {0}", stack.Count);

Output:

Total elements in Stack: 3
3
2
1
Total elements in Stack: 0

Peek() method in the Stack

The Peek() method returns the last added value of the stack but does not delete it. Calling the Peek () method on an empty stack throws an InvalidOperationException exception. Therefore, always check the items on the stack before searching for items using the Peek () method.

Example:

Stack stack = new Stack();
// Add element
stack.Push(1);
stack.Push(2);
stack.Push(3);

// print total number of element
Console.WriteLine("Total elements in Stack: {0}", stack.Count);

while (stack.Count > 0)
	Console.WriteLine(stack.Peek());  // It returns the last element and does not remove it from the stack

// print total number of element after calling Peek()
Console.WriteLine("Total elements in Stack: {0}", stack.Count);

Output:

Total elements in Stack: 3
3
Total elements in Stack: 3

Contain() method in the Stack

In C# if we want to check an element in the stack or not then we use Contain Method.

Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);
Console.WriteLine(stack.Contain(2));
Console.WriteLine(stack.Contain(5));

Output:

true
false

Properties

Property Usage
Count Gets the number of elements contained in the Stack.
IsSynchronized Gets a value indicating whether access to the Stack is synchronized (thread-safe).
SyncRoot Gets an object that can be used to synchronize access to the Stack.

More Methods

Method Usage
Clear() Removes all objects from the Stack.
Clone() Creates a shallow copy of the Stack.
Contains(Object) Determines whether an element is in the Stack.
CopyTo(Array, Int32) Copies the Stack to an existing one-dimensional Array, starting at the specified array index.
Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object)
GetEnumerator() Returns an IEnumerator for the Stack.
GetHashCode() Serves as the default hash function. (Inherited from Object)
GetType() Gets the Type of the current instance. (Inherited from Object)
MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object)
Peek() Returns the object at the top of the Stack without removing it.
Pop() Removes and returns the object at the top of the Stack.
Push(Object) Inserts an object at the top of the Stack.
Synchronized(Stack) Returns a synchronized (thread-safe) wrapper for the Stack.
ToArray() Copies the Stack to a new array.
ToString() Returns a string that represents the current object. (Inherited from Object)