C# Stack Contains() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Stack

Definition

In C#, Stack.Contains(item) checks whether an item is anywhere in a Stack<T>, not only on top. It returns true if the item is found and false if not. The stack is not changed.

Think of asking, "Is there a green plate somewhere in this pile?" You have to check the plates one by one. A stack has no fast lookup, so Contains is a linear scan, O(n). If you do this check very often on a big collection, keep a HashSet<T> next to the stack.

This is an instance member of Stack<T> (System.Collections.Generic). Call it on a stack variable, such as history.Contains(...). A Stack<T> is a class, so two variables can share one stack. It is last in, first out (LIFO): the newest item sits on top and leaves first. It is not thread-safe; for several threads use ConcurrentStack<T>.

Syntax

Pass the item you want to find. It returns a bool.

C#
Stack<string> colors = new Stack<string>();
colors.Push("red");
colors.Push("green");

bool a = colors.Contains("red");    // true (it is under green)
bool b = colors.Contains("pink");   // false
CallWhat it does
colors.Contains("red")true if some item in the stack equals "red", on top or buried.
colors.Contains("RED")false if the stack holds "red". String comparison here is case-sensitive.
colors.Contains(null)true only if a null was pushed. It does not throw.
colors.Peek()If you only care about the top item, Peek() is faster than Contains.

Contains compares with EqualityComparer<T>.Default. For string and numbers that means normal value equality. For your own classes it means reference equality (the same object) unless the class overrides Equals. There is no overload that accepts a custom comparer, so for case-insensitive search, convert your items or use LINQ.

Library declarations
C#
public bool Contains(T item);

Parameters

ParameterDescription
itemThe item to look for. It may be null for reference types.

Return Value

Return ValueDescription
booltrue if the item is in the stack. false if it is not, or if the stack is empty.

C# Examples

Example 1 — Check Which Colors Are in the Pile

Search for a buried color and one that is missing. Then check that searching did not change the stack.

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

class Program {
    static void Main() {
        Stack<string> colors = new Stack<string>();
        colors.Push("red");
        colors.Push("green");
        colors.Push("blue");

        Console.WriteLine(colors.Contains("red"));
        Console.WriteLine(colors.Contains("pink"));
        Console.WriteLine(colors.Count);
        Console.WriteLine(colors.Peek());
    }
}

How It Works

  1. Buried items count. Red is at the very bottom, under two other colors, and Contains still finds it. Depth does not matter.
  2. Not found. Nothing in the pile is pink, so the answer is False.
  3. Searching is read-only. Count is still 3 after two searches.
  4. The top is untouched. Peek() still shows blue, so the order was not disturbed either.

Example 2 — Case Matters, and null Can Be Found

Strings are compared exactly, including upper and lower case. A stack can also hold null, and Contains can find it.

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

class Program {
    static void Main() {
        Stack<string> tags = new Stack<string>();
        tags.Push("C#");

        Console.WriteLine(tags.Contains("C#"));
        Console.WriteLine(tags.Contains("c#"));
        Console.WriteLine(tags.Contains(null));

        tags.Push(null);
        Console.WriteLine(tags.Contains(null));
        Console.WriteLine(tags.Count);
    }
}

How It Works

  1. An exact match. "C#" is stored with that exact spelling, so the first search is True.
  2. Case-sensitive. The lowercase "c#" is a different string, so the second search prints False.
  3. No null yet. Asking for null before one was pushed gives False, and no exception is thrown.
  4. null is stored like any item. After Push(null), the search says True and Count is 2.

Example 3 — Push Only If Not Already There

Use Contains as a gatekeeper so each page id is stacked only once, then print the stack from the top down.

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

class Program {
    static void PushOnce(Stack<int> stack, int id) {
        if (!stack.Contains(id)) {
            stack.Push(id);
        }
    }

    static void Main() {
        Stack<int> visited = new Stack<int>();

        PushOnce(visited, 5);
        PushOnce(visited, 8);
        PushOnce(visited, 5);
        PushOnce(visited, 8);
        PushOnce(visited, 9);

        Console.WriteLine(visited.Count);
        Console.WriteLine(string.Join(", ", visited));
    }
}

How It Works

  1. A small helper. PushOnce pushes an id only when Contains says it is missing.
  2. Repeats are skipped. The second 5 and the second 8 are already in the stack, so their Push calls never run.
  3. Printed newest first. Three ids got in, in the order 5, 8, 9. A stack prints from the top down, so the line reads 9, 8, 5.
  4. Trade-off. Each check scans the stack, which is fine for short stacks. For thousands of items, keep a separate HashSet of ids for the check.

Frequently Asked Questions

It returns true if the item is anywhere in the stack, and false if it is not. It does not change the stack.
It is O(n). It checks the items one by one until it finds a match, so a tall stack takes longer to search.
Yes. Contains("Ben") does not match "ben". Convert both sides to the same case, or use LINQ with a comparer, for a case-insensitive search.
It uses the default equality. Without an Equals override, it only matches the very same object. Override Equals and GetHashCode in your class if you want matching by value.
Yes, if you pushed a null earlier. The call itself never throws for null.

Next: CopyTo()

Copy the stack's items into an existing array, top first, starting at a position you choose.

CopyTo() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful