C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Stack

The Stack class in C# is part of the System.Collections namespace and represents a last-in, first-out (LIFO) collection of objects. This tutorial will cover the following topics related to the Stack class in C#:

  • Creating a Stack
  • Pushing elements onto a Stack
  • Popping elements off a Stack
  • Peeking at the top element
  • Checking if a Stack is empty
  • Looping through a Stack

Let's begin!

  • Creating a Stack

To create a new instance of the Stack class, use the Stack constructor:

using System.Collections;

Stack stack = new Stack();
  • Pushing elements onto a Stack

To add an element to the top of a Stack, use the Push method:

stack.Push(1);
stack.Push(2);
stack.Push(3);

In this example, we push three integer values onto the Stack.

  • Popping elements off a Stack

To remove and return the top element of a Stack, use the Pop method:

int value = (int)stack.Pop();  // Cast the value to int
Console.WriteLine(value);  // Output: 3
  • Peeking at the top element

To return the top element of a Stack without removing it, use the Peek method:

int value = (int)stack.Peek();  // Cast the value to int
Console.WriteLine(value);  // Output: 2
  • Checking if a Stack is empty

To check if a Stack is empty, you can use the Count property:

bool isEmpty = stack.Count == 0;
Console.WriteLine(isEmpty);  // Output: False
  • Looping through a Stack

To loop through the elements of a Stack, you can use a foreach loop:

foreach (int item in stack)
{
    Console.WriteLine(item);
}

This will output:

2
1

Alternatively, you can use a while loop and the Pop method to loop through the elements and remove them from the Stack:

while (stack.Count > 0)
{
    int value = (int)stack.Pop();
    Console.WriteLine(value);
}

This will output:

2
1

That's it! You've now learned how to use the Stack class in C# to store and manipulate a last-in, first-out (LIFO) collection of objects. The Stack class is useful for scenarios where you need a simple data structure to manage elements in a LIFO manner, such as implementing undo and redo functionality, parsing expressions, or managing function call stacks. Note that the Stack class is not type-safe and requires casting when working with elements. If you need a type-safe stack, consider using the Stack<T> class from the System.Collections.Generic namespace instead.

  1. How to use Stack in C#

    Stack in C# represents a Last-In-First-Out (LIFO) collection of objects.

    using System;
    using System.Collections;
    
    class Program
    {
        static void Main()
        {
            Stack stack = new Stack();
            stack.Push("Apple");
            stack.Push("Orange");
            stack.Push("Banana");
    
            while (stack.Count > 0)
            {
                Console.WriteLine(stack.Pop());
            }
        }
    }
    
  2. Push and pop operations in C# Stack

    Use Push to add an element and Pop to remove the top element.

    Stack<int> numbers = new Stack<int>();
    numbers.Push(1);
    int topNumber = numbers.Pop(); // Retrieves and removes the top element.
    
  3. Peek method in C# Stack

    Peek retrieves the top element without removing it.

    string topFruit = stack.Peek(); // Retrieves but does not remove the top element.
    
  4. Using generic Stack<T> in C#

    The generic version allows type-safe handling.

    Stack<string> fruits = new Stack<string>();
    fruits.Push("Apple");
    string topFruit = fruits.Pop();
    
  5. Iterating through a Stack in C#

    Use a foreach loop or convert the Stack to an array.

    foreach (var item in stack)
    {
        // Process each item
    }
    
  6. Using Stack for expression evaluation in C#

    Stacks are useful for evaluating expressions with parentheses.

    string expression = "3 + (2 * 5)";
    // Evaluate expression using a stack-based algorithm