C# Stack

C# collections

In C#, a Stack is a Last In First Out (LIFO) data structure.

Stack is suitable for storing and processing data in sequence, where the most recently added element is removed first.

Stack represents aLast-in, first-outCollection of objects. When you need last-in, first-out access to items, use a stack. When you add an item to the stack, it is calledPushelement, and when you remove an item from the stack, it is calledPopElement.

Stack provides two implementations:

  1. non-genericStack(System.Collections.Stack): Supports storing objects of any type (requires boxing and unboxing operations).
  2. GenericsStack<T>(System.Collections.Generic.Stack<T>): Supports strongly typed objects, avoids boxing and unboxing, and improves performance.

Stack features:

  • Last-in, first-out: The last element pushed onto the stack is popped first.
  • Dynamic size: The capacity of the stack adjusts dynamically as needed.
  • Generic support: throughStack<T>Provides type safety, avoiding type conversion errors.
  • Not thread-safe: defaultStackandStack<T>None of them are thread-safe.

Methods and properties of the Stack class

The table below listsStackSome common class membersProperty:

Attribute NameTypeDescription
CountintGets the number of elements in the stack.
SyncRootobjectGets an object used to synchronize access to the stack (non-generic).
IsSynchronizedboolIndicates whether access to the stack is synchronized (thread-safe, alwaysfalse)。
td>Gets the number of elements contained in the Stack.

The table below listsStackSome common class membersMethods:

Method NameReturn TypeDescription
Element operations
Push(object item)voidPushes an element onto the top of the stack.
Pop()objectRemoves and returns the element at the top of the stack.
Peek()objectReturns the element at the top of the stack without removing it.
Clear()voidRemoves all elements from the stack.
Check and copy
Contains(object item)boolDetermines whether an element exists in the stack.
ToArray()object[]Copies the elements in the stack to a new array (with the order reversed).
Clone()objectCreates a shallow copy of the current stack.
CopyTo(Array array, int index)voidCopies the elements in the stack to an existing array, starting at the specified index.
Enumerator support
GetEnumerator()IEnumeratorReturns an enumerator used to iterate through the elements in the stack.
Thread Safety
Synchronized(Stack stack)StackReturns a thread-safe stack wrapper.

Example

The following example demonstrates the use of a stack (Stack).

Non-generic stack:

Example

using System;
using System.Collections;

namespace CollectionsApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack st = new Stack();

            st.Push('A');
            st.Push('M');
            st.Push('G');
            st.Push('W');
           
            Console.WriteLine("Current stack: ");
            foreach (char c in st)
            {
                Console.Write(c + " ");
            }
            Console.WriteLine();
           
            st.Push('V');
            st.Push('H');
            Console.WriteLine("The next poppable value in stack: {0}",
            st.Peek());
            Console.WriteLine("Current stack: ");          
            foreach (char c in st)
            {
               Console.Write(c + " ");
            }
            Console.WriteLine();

            Console.WriteLine("Removing values ");
            st.Pop();
            st.Pop();
            st.Pop();
           
            Console.WriteLine("Current stack: ");
            foreach (char c in st)
            {
               Console.Write(c + " ");
            }
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Current stack: 
W G M A
The next poppable value in stack: H
Current stack: 
H V W G M A
Removing values
Current stack: 
G M A

Generic stack:

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Stack<int> stack = new Stack<int>();

        // push
        stack.Push(10);
        stack.Push(20);
        stack.Push(30);

        // View the top of the stack
        Console.WriteLine($"Peek: {stack.Peek()}"); // Output: 30

        // pop
        Console.WriteLine($"Pop: {stack.Pop()}"); // Output: 30

        // Remaining stack
        Console.WriteLine("Remaining items:");
        foreach (var item in stack)
        {
            Console.WriteLine(item); // Output: 20, 10
        }
    }
}

Difference between Stack and Stack<T>

Stack (non-generic)

  • Stores objects asobjecttype.
  • Requires explicit type casting when used, which may cause runtime exceptions.

Stack<T> (Generic)

  • Provides type safety and avoids type conversion issues.
  • Better performance because it avoids the overhead of boxing and unboxing.

C# collections

other extensions