Open In App

Stack Class in C#

Last Updated : 11 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Stack<T> in C# is a collection that stores elements in LIFO (Last In, First Out) order. This means the last element inserted is the first one removed. It is defined in the System.Collections.Generic namespace and provides fast insertion and removal from the top of the stack.

  • LIFO order: Last element pushed is the first to be popped.
  • Generic type-safe collection (Stack<int>, Stack<string>, etc.).
  • Duplicates allowed (unlike sets).
  • Dynamic resizing: Capacity grows automatically as needed.
  • Efficient operations: Push, Pop, and Peek work in O(1) time.

Example: This example demonstrates how to use Stack to push and pop elements in LIFO order.

C#
using System;
using System.Collections.Generic;

public class Geeks {
    public static void Main(string[] args)
    {
        // Create a new stack
        Stack<int> s = new Stack<int>();

        // Push elements onto the stack
        s.Push(1);
        s.Push(2);
        s.Push(3);
        s.Push(4);

        // Pop elements from the stack
        while (s.Count > 0) {
            Console.WriteLine(s.Pop());
        }
    }
}

Output
4
3
2
1

Declaration of Stack

1. Generic Stack: Holds elements of a specific type.

Stack<T> stackName = new Stack<T>();

Non-Generic Stack: Can hold elements of any type but requires casting when retrieving elements.

Stack stack = new Stack(); // Non-generic stack

Example: Example demonstrating both generic and non-generic Stack usage

C#
using System;
using System.Collections;
using System.Collections.Generic;

public class Geeks {
    static public void Main()
    {
        // Non-generic Stack (can hold any type)
        Stack stack = new Stack();
        stack.Push("GFG");
        stack.Push(1);
        stack.Push(2.5);
        stack.Push(null);
        stack.Push("Geeks123");

        Console.WriteLine("Non-Generic Stack:");
        foreach (var item in stack) {
            Console.WriteLine(item);
        }

        Console.WriteLine();

        // Generic Stack (holds only strings)
        Stack<string> genericStack = new Stack<string>();
        genericStack.Push("GFG");
        genericStack.Push("GeeksForGeeks");
        genericStack.Push("Stack Example");

        Console.WriteLine("Generic Stack:");
        foreach (var item in genericStack) {
            Console.WriteLine(item);
        }
    }
}

Output
Non-Generic Stack:
Geeks123

2.5
1
GFG

Generic Stack:
Stack Example
GeeksForGeeks
GFG

Constructors

The Stack<T> class provides three constructor which are listed below in the table:

Constructor

Description

Stack()

Initializes an empty stack with the default initial capacity.

Stack(ICollection)

Initializes a new stack containing elements copied from a specified collection.

Stack(Int32)

Initializes an empty stack with the specified initial capacity (or the default if the given capacity is smaller).

Example: This example demonstrates the basic operations of Stack such as adding an element, checking the Stack size and viewing the top element without modify the stack.

C#
using System;
using System.Collections;

class Geeks {
    public static void Main(){
        // Creating a Stack
        Stack s = new Stack();

        // Pushing elements into the Stack
        s.Push(10);
        s.Push(20);
        s.Push(30);
        s.Push(40);
        s.Push(50);
        s.Push(60);

        // Displaying the count of elements in the Stack
        Console.Write("Total elements in Stack: ");
        Console.WriteLine(s.Count);

        // Displaying the top element of the Stack without removing it
        Console.WriteLine("Top element is: " + s.Peek());

        // Displaying the top element of the Stack again
        Console.WriteLine("Top element again is: " + s.Peek());

        // Displaying the updated count of elements
        Console.Write("Updated count of elements: ");
        Console.WriteLine(s.Count);
    }
}

Output
Total elements in Stack: 6
Top element is: 60
Top element again is: 60
Updated count of elements: 6

Properties

The Stack<T> class provides several properties to access its state.

Property

Description

Count

Returns the number of elements currently in the stack.

IsSynchronized

Indicates whether the stack is thread-safe.

SyncRoot

Provides an object to synchronize access to the stack.

Example: This example demonstrates the total number of elements in the Stack.

C#
using System;
using System.Collections;

class Geeks {
    public static void Main(){
        // Creating a Stack
        Stack s = new Stack();

        // Inserting the elements into the Stack
        s.Push(10);
        s.Push(20);
        s.Push(30);
        s.Push(40);
        s.Push(50);
        s.Push(60);

        // Displaying the count of elements in the Stack
        Console.Write("Total number of elements in the Stack are: ");
        Console.WriteLine(s.Count);
    }
}

Output
Total number of elements in the Stack are: 6

Methods

MethodDescription
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.
GetEnumerator()Returns an IEnumerator for the Stack.
GetHashCode()Serves as the default hash function.
GetType()Gets the Type of the current instance.
MemberwiseClone()Creates a shallow copy of the current 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.

Example: This example demonstrates how to use clear() to clear all the elements from the stack.

C#
using System;
using System.Collections;

class Geeks {
    public static void Main(){
        // Creating a Stack
        Stack s = new Stack();

        // Inserting elements into the Stack
        s.Push(10);
        s.Push(20);
        s.Push(30);
        s.Push(40);
        s.Push(50);
        s.Push(60);

        // Displaying the count of elements before clearing the Stack
        Console.Write("Total elements in Stack before clear: ");
        Console.WriteLine(s.Count);

        // Removing all elements from the Stack
        s.Clear();

        // Displaying the count of elements after clearing the Stack
        Console.Write("Total elements in Stack after clear: ");
        Console.WriteLine(s.Count);
    }
}

Output
Total elements in Stack before clear: 6
Total elements in Stack after clear: 0

Example: This example demonstrates how to check if a specific element is present in a stack using the Contains().

C#
using System;
using System.Collections;

class Geeks {
    public static void Main()
    {
        // Creating a Stack of strings
        Stack s = new Stack();

        // Inserting the elements into the Stack
        s.Push("Geek1");
        s.Push("Geek2");
        s.Push("Geek3");
        s.Push("Geek4");
        s.Push("Geek5");

        // Checking whether the element is present in the Stack or not
        Console.WriteLine("The element Geek2 is present? :" + s.Contains("Geek2"));
        Console.WriteLine("The element Geek10 is present? :" + s.Contains("Geek10"));
    }
}

Output
The element Geek2 is present? :True
The element Geek10 is present? :False