Updated on

A stack in C# is a collection that gives items back in last-in, first-out (LIFO) order. We work with the generic Stack<T> class through three methods: Push() adds an item on top, Pop() removes the top item, and Peek() reads it without removing it.

We’ll cover both the generic and the non-generic stack, what happens when we pop an empty one, and how to share a stack between threads.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

What Is a Stack in C# and When Do We Use One?

A stack in C# is a collection that hands items back in last-in, first-out (LIFO) order. The item we added most recently is the first one we get back.

In modern code we use the generic Stack<T> from System.Collections.Generic. Three methods do most of the work. Push() puts an item on top, Pop() removes and returns the top item, and Peek() returns the top item without removing it. Count tells us how many items are inside.

On an empty stack, Pop() and Peek() throw an InvalidOperationException. TryPop() and TryPeek() return false instead, so we use them whenever the stack might be empty.

We reach for a stack when the newest item is the one we need next: an undo history, the back button in a browser, matching brackets in an expression, or walking a tree without recursion.

When the oldest item should come out first, a stack is the wrong tool and we want a queue.

Let’s imagine having to stack some dining plates and then having to set them on a table. The dining plate on the top (the last added to the stack) will be removed first, while the one on the bottom will remain on the stack for longer.

A practical implementation in the software would be an undo-redo operation in a common editor, where we can use a stack to store all the performed operations by a user and then use it to retrieve them from the most recently performed action to the oldest one.

LIFO is different from FIFO. If we need items back in the order we added them, a first-in, first-out queue is the collection for that.

We can create a stack in C# using the Stack class. When we add an item to a stack we say that we are pushing the item, while when we remove it we are popping the item.

When we initialize a stack, it has a capacity: the number of elements its internal array can hold before it has to grow. The capacity increases as we add more items. The Count property, on the other hand, tells us how many elements the stack actually contains.

A stack in four steps: items 1, 2 and 3 are pushed one on top of the other, then item 3 is popped off the top

Generic and Non-Generic Collections

C# includes the generic version Stack<T> as well, which is more commonly used than the non-generic one. If we opt for the non-generic Stack, we can add elements of different types (a string, an integer, etc for example).

Since the non-generic Stack stores every item as object, we have to cast each item back to its real type when we read it, and that check happens at run time. Value types such as int are also boxed on the way in, which costs an allocation per item. Our article on boxing and unboxing shows what that costs.

The generic version, instead, permits us to specify the same type <T> for all the items we are going to add to the collection. Stack<T> collection is in the System.Collections.Generic namespace.

Stack in C# Constructors

Both the non-generic and the generic versions of Stack have three constructors.

Let’s start with the non-generic case, which needs using System.Collections; at the top of the file:

Stack firstNonGenericStack = new Stack();

It initializes an empty stack, having the default initial capacity. For the non-generic Stack class, the default initial capacity is ten. Invoking firstNonGenericStack.Count we will obtain zero since it doesn’t contain any element yet.

The second constructor is Stack(ICollection):

List<string> letters = ["a", "b", "c"];
Stack secondNonGenericStack = new Stack(letters);

This constructor creates a Stack from any collection that implements the ICollection interface. In this case, we created a stack with the elements from the letters list, so secondNonGenericStack.Count returns three. The initial capacity is ten, not three, because the non-generic stack never starts below its default capacity.

The last constructor is Stack(Int32), where the integer represents the initial capacity of Stack:

Stack thirdNonGenericStack = new Stack(5);

Here, we ask for an initial capacity of five. The non-generic stack rounds that up to its default of ten, so a value below ten makes no difference.

Let’s see what happens with the generic counterparts of the constructors:

Stack<int> firstGenericStack = new Stack<int>();

We created a Stack that can store only int items, having a default initial capacity. For the generic stack, the default initial capacity is zero. 

The second constructor takes an IEnumerable<T> as input, and it creates a stack starting from this collection:

Stack<string> secondGenericStack = new Stack<string>(letters);

In this case, we created secondGenericStack containing the elements from the letters list.

The constructor copies the items in the order the list returns them, so the last element of the list ends up on top:

Console.WriteLine(secondGenericStack.Peek());
Console.WriteLine(string.Join(", ", secondGenericStack));
c
c, b, a

When we enumerate a stack, we get the items from the top down, which is the reverse of the list we started with. A collection expression such as Stack<int> numbers = [1, 2, 3]; doesn’t compile, because Stack<T> has no Add() method. We go through the constructor instead.

Finally, the third constructor for the generic case is Stack<T>(Int32):

Stack<int> thirdGenericStack = new Stack<int>(5);

It is a stack that contains only integer values with a capacity of five.

What Are the Main Stack Methods in C#?

Stack<T> has a small surface, and five members cover nearly everything we do with it.

Push(item) adds an item to the top. Pop() removes the top item and returns it. Peek() returns the top item and leaves it in place. Count returns the number of items. Clear() removes all of them.

The generic stack adds two safer variants. TryPop(out item) and TryPeek(out item) return false on an empty stack instead of throwing an exception. That makes them the natural choice in loops and anywhere we can’t be sure the stack holds anything.

A few helpers round it out. Contains(item) searches the whole stack, ToArray() copies the items out from top to bottom, and EnsureCapacity() and TrimExcess() manage the internal array.

Push(), Pop() and Peek() are cheap. Push() only gets expensive on the call that has to grow the internal array, because every item is copied into a bigger one.

Count

The Count property returns the number of elements stored in Stack:

Stack lettersStack = new Stack(letters);

Console.WriteLine($"lettersStack contains {lettersStack.Count} items"); //lettersStack contains 3 items

Push()

We can add an item to Stack by using the Push method. For a non-generic Stack, like lettersStack, a push operation is allowed for any item of a type derived from object.

So let’s define a class Page we’re going to work with, in its own Page.cs file:

public class Page
{
    public Page(string title, DateTime lastUpdateTime)
    {
        Title = title;
        LastUpdateTime = lastUpdateTime;
    }

    public string Title { get; set; }

    public DateTime LastUpdateTime { get; set; }
}

We can add a Page to the non-generic lettersStack:

Page page = new Page("New page", DateTime.Now);

Console.WriteLine($"lettersStack contains {lettersStack.Count} items"); //lettersStack contains 3 items
lettersStack.Push(page);
lettersStack.Push(1);
lettersStack.Push("hello");

Console.WriteLine($"lettersStack contains {lettersStack.Count} items");//lettersStack contains 6 items

The number of items contained in lettersStack increases as we push new elements.

Since in the generic case Stack<T> handles the elements of the same type, we can define a pageStack stack which can handle Page items and then push two pages into it:

Stack<Page> pageStack = new Stack<Page>();

var page1 = new Page("The first visited page", DateTime.Now);
var page2 = new Page("The second visited page", DateTime.Now);

pageStack.Push(page1);
pageStack.Push(page2);

For both the generic and non-generic cases, when a push finds the internal array full, the stack allocates an array twice as big and copies the items over. The one exception is a generic stack that starts with an empty array, such as one created with new Stack<T>(): it makes room for four items on the first push.

If we know roughly how many items are coming, we can skip the copies and size the array once:

var history = new Stack<Page>();
history.EnsureCapacity(100);

Console.WriteLine($"history can hold {history.Capacity} pages before it grows");
history can hold 100 pages before it grows

Peek()

The Peek() method returns the last added element, but it doesn’t modify the stack:

object? lastAddedItem = lettersStack.Peek(); 
var lastVisitedPage = pageStack.Peek();

Console.WriteLine($"the first retrieved element in lettersStack is {lastAddedItem}");
Console.WriteLine($"the first retrieved element in pageStack is {lastVisitedPage.Title}");
Console.WriteLine($"lettersStack contains {lettersStack.Count} items");
Console.WriteLine($"pageStack contains {pageStack.Count} items");

In both cases, the Count property doesn’t change:

the first retrieved element in lettersStack is hello
the first retrieved element in pageStack is The second visited page
lettersStack contains 6 items
pageStack contains 2 items

If we call Peek() method on an empty Stack, it throws a System.InvalidOperationException: Stack empty exception. For the generic Stack (pageStack), we can use the TryPeek(out T result) method, which checks if Stack is empty and if there are any items to peek at.

If there’s an object in Stack, it returns true and the object as an out value, false otherwise:

var result = pageStack.TryPeek(out var topPage);

Console.WriteLine($"TryPeek returns: {result}");
Console.WriteLine($"The title of the topPage in pageStack is: {topPage?.Title}");
Console.WriteLine($"pageStack contains {pageStack.Count} items");

The output parameter is the page on the top of Stack:

TryPeek returns: True
The title of the topPage in pageStack is: The second visited page
pageStack contains 2 items

Pop()

The Pop() method removes and returns the last element added to Stack, and it is equivalent for both the non-generic and generic cases:

lastAddedItem = lettersStack.Pop();
lastVisitedPage = pageStack.Pop();

Console.WriteLine($"The first retrieved element in lettersStack is {lastAddedItem}");
Console.WriteLine($"The first retrieved element in pageStack is {lastVisitedPage.Title}");
Console.WriteLine($"lettersStack contains {lettersStack.Count} items");
Console.WriteLine($"pageStack contains {pageStack.Count} items");

In this case, lastAddedItem is hello and lastVisitedPage is "The second visited page", since they are the last added elements to lettersStack and pageStack respectively.

Both lettersStack and pageStack won’t contain anymore these elements, since we removed them using Pop():

The first retrieved element in lettersStack is hello
The first retrieved element in pageStack is The second visited page
lettersStack contains 5 items
pageStack contains 1 items

If we call Pop() method to an empty Stack, it will throw a System.InvalidOperationException: Stack empty exception. To avoid this issue, for the generic stack (pageStack) there is the TryPop(out T result) method, returning true if there is an object on the top of Stack, false otherwise:

result = pageStack.TryPop(out topPage);

Console.WriteLine($"TryPop returns: {result}");
Console.WriteLine($"The title of the topPage in pageStack was: {topPage?.Title}");
Console.WriteLine($"pageStack contains {pageStack.Count} items");

This will print out:

TryPop returns: True
The title of the topPage in pageStack was: The first visited page
pageStack contains 0 items

TryPop() took the last page, so the stack is now empty, and another call would return false.

Clear()

The Clear() method removes all the elements from a stack. After this operation, Stack will be empty:

lettersStack.Clear();

Console.WriteLine($"lettersStack contains {lettersStack.Count} items");

As we expect, lettersStack contains 0 items:

lettersStack contains 0 items

How Do We Check if a Stack Is Empty in C#?

We check Count. A stack is empty when stack.Count == 0, and Stack<T> has no IsEmpty property to call instead.

Most of the time, though, we check because we want the top item next, and TryPop() does both jobs in one call. On an empty stack it returns false and sets the out value to the type’s default, so we need neither a try/catch nor a separate Count check.

The same method gives us the usual way to process a whole stack. A while (stack.TryPop(out var item)) loop takes items from the top until none are left, and it ends on its own when the stack runs dry.

The non-generic Stack has no TryPop() or TryPeek(). There, checking Count > 0 before every Pop() or Peek() is the safe pattern.

ConcurrentStack<T>, which comes up in the next section, does have an IsEmpty property.

Let’s see both in action with a small undo history:

var undoStack = new Stack<string>();

Console.WriteLine($"Is the stack empty? {undoStack.Count == 0}");

if (!undoStack.TryPop(out var lastAction))
{
    Console.WriteLine("Nothing to undo");
}
Is the stack empty? True
Nothing to undo

Now let’s push three actions and undo all of them:

undoStack.Push("Type 'Hello'");
undoStack.Push("Make it bold");
undoStack.Push("Delete a word");

while (undoStack.TryPop(out var action))
{
    Console.WriteLine($"Undo: {action}");
}

Console.WriteLine($"Is the stack empty? {undoStack.Count == 0}");
Undo: Delete a word
Undo: Make it bold
Undo: Type 'Hello'
Is the stack empty? True

The last action comes back first, which is exactly what an undo button needs. Here is what every member does when the stack is empty:

MemberWhat it doesOn an empty stackCost
Push(item)Adds an item on topAdds the first itemO(1), or O(n) when the array grows
Pop()Removes and returns the top itemThrows InvalidOperationExceptionO(1)
Peek()Returns the top item and keeps itThrows InvalidOperationExceptionO(1)
TryPop(out item)Pops without throwingReturns false, item is the default value-
TryPeek(out item)Peeks without throwingReturns false, item is the default value-
CountReturns the number of itemsReturns 0O(1)
Contains(item)Searches every itemReturns falseO(n)
ToArray()Copies the items, top firstReturns an empty arrayO(n)
Clear()Removes every itemDoes nothingO(n)

Is Stack in C# Thread-Safe?

No. Neither Stack<T> nor the non-generic Stack is safe to change from several threads at once. The Microsoft Learn page for Stack<T> puts it plainly: “Any instance members are not guaranteed to be thread safe.”

Several threads can read the same stack safely as long as nothing modifies it. Once one thread calls Push() or Pop() while another thread reads or writes, items can go missing or the stack can end up in a broken state.

For the non-generic Stack, Stack.Synchronized() returns a wrapper that locks around each call.

For generic code, the type to use is ConcurrentStack<T> from System.Collections.Concurrent. It is a separate, lock-free class with Push(), TryPop() and TryPeek(), and no plain Pop().

We can also put our own lock around a regular Stack<T>. That is the better choice when a pop has to happen together with other work, as one step.

Non-Generic Case

Sometimes, we need to access the same stack from multiple threads and this can lead to unexpected behaviors. To avoid these problems, we can use the Synchronized wrapper, used to return a thread-safe wrapper for Stack:

Stack synchronizedStack = Stack.Synchronized(lettersStack);

Stack.Synchronized takes as input the non-generic Stack and returns a wrapper around it. Now, if we call the IsSynchronized property (that checks if the access to Stack is thread-safe),  for both:

Console.WriteLine($"lettersStack is thread-safe: {lettersStack.IsSynchronized}"); //False
Console.WriteLine($"synchronizedStack is thread-safe: {synchronizedStack.IsSynchronized}"); //True

Keep in mind that the wrapper locks each call on its own. Enumerating the stack with foreach is still not thread-safe, so we need to lock the whole loop if other threads can write at the same time.

Generic Case

For the generic stack, we should use ConcurrentStack<T>, which needs using System.Collections.Concurrent;:

ConcurrentStack<Page> threadSafePageStack = new ConcurrentStack<Page>();

Unlike Stack.Synchronized(), ConcurrentStack<T> doesn’t wrap a regular stack. It’s a separate class that keeps its items in a linked list and updates the top with atomic operations instead of a lock, so many threads can push and pop at once. Its API differs a little: there is no Pop(), only TryPop(), because another thread might empty the stack between our check and our call.

Let’s push a hundred pages from parallel threads:

Parallel.For(0, 100, i => threadSafePageStack.Push(new Page($"Page {i}", DateTime.Now)));

Console.WriteLine($"threadSafePageStack contains {threadSafePageStack.Count} items");
threadSafePageStack contains 100 items

All hundred pages made it in. We cover the rest of its API, including PushRange() and TryPopRange(), in our ConcurrentStack guide.

Conclusion

In this article, we’ve learned about both the non-generic and the generic versions of Stack in C#. We’ve shown how to add and remove elements to stacks, and how to implement a thread-safe stack if we need to.

When the stack might be empty, TryPop() and TryPeek() save us an exception, and when several threads share it, ConcurrentStack<T> is the class to reach for. Stacks are one of many collections in .NET, and the overview helps when we’re not sure a stack is the right one.

Tested with .NET 10.0.10 and xUnit 2.9.3.