Posted on 4/22/2025 7:44:41 AM by Admin

Data Structures – Stacks in C# (LIFO)

In previous articles, we have covered arrays and lists used to store data sequentially. So, understanding stacks would not be difficult for you. Stack is another intuitive concept in DSA that operates on a simple yet powerful principle known as LIFO – Last In, First Out.

As its name states, the last item entered in the stack is the first item taken out. For example, consider that you have a stack of plates. When you add a new plate, you place it on top. Similarly, when you want a plate, you take the one at the top. Hence, the plate added at last would be taken out first. This is how the LIFO principle works.

Consider a container open from one side, i.e., on the top. If you stack some items in it, say the matchboxes, the last matchbox you put will be at the top. So, when you need a matchbox, you take out the one at the top instead of the last. This is how a stack data structure works. Let's explore the stacks more and learn how to perform different operations.

What is a Stack?

A stack is a collection of items arranged in a way that the item added at last is the first item that comes out. As stated earlier, it follows the LIFO principle. Like List<T>, it is also a generic class Stack<T> that can work with generic data types. To work with stacks, you must add the System.Collections.Generic; namespace in your program.

I'll skip that here since I have already demonstrated adding this namespace to your program in the previous article. Please add the namespace in your program before trying the examples in this lesson.

Declaring a Stack

You can specify the data type and the name of the stack while declaring. The items in the stack are added via the Push() method defined in the generic class.

Syntax:


Stack<datatype> stackname = new Stack<datatype>();

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
      
    Stack<string> names = new Stack<string>();
}
}

Adding Elements to the Stack

The Stack<T> class provides the push() method to add elements at the top of the stack.

Syntax:


stackname.Push(element);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
      
    Stack<string> names = new Stack<string>();
    names.Push("James"); //Adds James at top
    names.Push("Jones"); //Adds Jones at top
    names.Push("Smith"); //Adds Smith at top
}
}

Removing Elements from Stack

The Stack<T> class also provides the Pop() method to remove an element from the top of the stack.

Syntax:


stackname.Pop()

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
    Stack<string> names = new Stack<string>();
    names.Push("James");
    names.Push("Jones");
    names.Push("Smith");
    names.Pop(); //Removes Smith from the top. Now, Jones is at the top. 
}
}

Returning the Top Element

The returning here refers to taking a look at the top element in a stack. The Peek() method is used to examine the top element of the stack without removing it. The Peek() method will throw an exception if a stack is empty.

Syntax:


stackname.Peek();

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
  Stack<string> names = new Stack<string>();
    names.Push("James");
    names.Push("Jones");
    names.Push("Smith");
    Console.Write(names.Peek()); //Returns Smith. 
}
}

Getting the Number of Elements in a Stack

You can use the Count property to find the number of elements in a stack.

Syntax:


stack_name.Count;

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
   Stack<int> numbers = new Stack<int>();
    numbers.Push(1);
    numbers.Push(2);
    numbers.Push(3);
    Console.Write(numbers.Count); //Returns 3
    Console.ReadKey();
  }
}

Checking if a Stack is Empty

C# does not provide a specific function or property to check if the stack contains elements or not. So, we use the Count property to determine this.

You can specify a condition where if the count of elements is 0, the stack should be shown as empty; otherwise, it contains the elements.

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  public static bool isEmpty(Stack<int> stk)  //Function to determine if a stack is empty. 
  {
      if (stk.Count == 0)  //if the stack passed through the parameter has 0 elements, it resturns true. 
      {
          return true;
      }      
      else
      {
          return false;
      }
  }
  static void Main() {
    Stack<int> numbers = new Stack<int>();
    numbers.Push(1);
    numbers.Push(2);
    numbers.Push(3);
    Console.Write(isEmpty(numbers));  //Calling the isEmpty function. Returns false. 
    Console.ReadKey();
  }
}

In the above code, I have defined a custom method that checks whether a stack has elements. If yes, it returns true. If not, it returns false.

Uses of Stack

The stacks are widely used in software applications due to their LIFO functionality. Some of the use cases include:

Undo/Redo Functionality

The undo and redo functionality in most applications are implemented with the help of stacks. Whenever a user performs an action, it is pushed onto the "Undo" stack. When the user clicks Undo, the stack's last item is popped and pushed to the "Redo" stack. The reversed functionality is implemented on the Redo.

Function Call Stack

Another notable application of stacks is function calls. The operating system and runtime environments use stacks called call stacks to manage the function calls during program execution. When a function is called, information like return address and local variables are pushed to the stack. When the function has been executed, this information pops out of the stack, and the program returns to the next instructions.

When used properly, stacks can be really beneficial for convenient data storage. They provide an efficient way to store, retrieve, delete, and perform different operations on the data. In the next article, we will learn about the Queues, a data structure that works on FIFO (First In, First Out).


Data Structures -  Arrays in C#
Data Structures - Arrays in C#
Data Structures – Lists in C# (Dynamic Arrays)
Data Structures – Lists in C# (Dynamic Arrays)