C# Stack with example

In C# stack is a first-in, last-out data structure with methods to push an item onto the top of the stack and pop an item from the top of the stack and examine the item at the top of the stack without removing it. The stack maintains a last-in, first-out (LIFO) order. This means that the first item you add is the last item to be popped (removed from the stack). 

An element joins the stack at the top (the push operation) and leaves the stack at the top (the pop operation). To visualize this, think of a stack of dishes: new dishes are added to the top and dishes are removed from the top, making the last dish to be placed on the stack the first one to be removed. (The dish at the bottom is rarely used and will inevitably require washing before you can put any food on it—because it will be covered in grime!)

Declaring a Stack in C#

Stack allows Null values and we can have duplicate vaues, to declare a stack in C#, you have following code

Stack MyStack = new Stack(); 

As elements are added to a Stack, the capacity is automatically increased as required through reallocation.

Commonly used methods in stack are:

  • Push: Add (Push) an item in the Stack data structure
    MyStack.Push(5);
    MyStack.Push(1);
    MyStack.Push(2);?
  • Pop: Pop return the last Item from the Stack
    MyStack.Pop(); //removes the top object from stack?
  • Contains: Check the object contains in the Stack
    MyStack.Contains(5)?
  • Clear: Remove all objects from stack
  • Peek: Returns the top object of the stack without removing it.
    MyStack.Peek(); // return the top element of stack?

stack-csharp-implementation-puh-pop-min.png

C# Stack example ( Push, POP, Peek, Contains example )

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		Stack MyStack = new Stack(); 
		MyStack.Push(5);
		MyStack.Push(1);
		MyStack.Push(2); //last item to be pushed on stack ( means at top)
		
		//print stack using foreach loop
		Console.WriteLine("Stack After Pushing items:");
		PrintStack(MyStack);
		
		Console.WriteLine();
		//remove item from stack
		MyStack.Pop();
		
		//now check stack again
		Console.WriteLine("Stack After pop: ");
		PrintStack(MyStack);
		
		Console.WriteLine();
		
		//check if element exists using .Contains
		Console.WriteLine("5 Exists in Stack? : "+MyStack.Contains(5));		
		Console.WriteLine();
		
		//check top item using Peek method
		Console.WriteLine("Top Item of stack is : "+MyStack.Peek());	
	}
	
	//print stack method
	public static void PrintStack(Stack MyStack)
	{
		foreach(var item in MyStack)
		{
			Console.WriteLine(item);
		}
	}

}

Output:

Stack After Pushing items:
2
1
5

Stack After pop: 
1
5

5 Exists in Stack? : True

Top Item of stack is : 1


Share Tweet