C# HashSet Contains() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In C#, HashSet.Contains(item) answers one question: is this item in the set? It returns true or false. It never changes the set.

This is the thing a HashSet is best at. The set does not scan every item. It jumps almost straight to the right spot, so the answer takes about the same short time (average O(1)) whether the set holds ten items or ten million. List.Contains, by comparison, checks the items one by one.

This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.Contains(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order.

Syntax

Call Contains with the item you are looking for and use the bool result in an if.

C#
HashSet<string> colours = new HashSet<string> { "red", "green", "blue" };
bool a = colours.Contains("green");   // true
bool b = colours.Contains("pink");    // false
if (colours.Contains("red")) { /* do something */ }
CallWhat it does
colours.Contains("green")Returns true when "green" is stored in the set.
colours.Contains("pink")Returns false when no equal item is stored. No exception.
!colours.Contains(x)Use the ! sign to test for items that are missing.

Contains uses the set's comparer. By default "Red" and "red" are different. A set built with StringComparer.OrdinalIgnoreCase ignores case. Contains(null) is allowed for reference types and is true only if you added a null item.

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

Parameters

ParameterDescription
itemRequired. The item to look for. The set decides "equal" with its comparer (for example Equals and GetHashCode).

Return Value

Return ValueDescription
booltrue if the set contains an equal item. false if it does not.

C# Examples

Example 1 — Look Up Colours

Build a set of three colours and ask about one that is there and one that is not.

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

class Program {
    static void Main() {
        HashSet<string> colours = new HashSet<string> { "red", "green", "blue" };

        Console.WriteLine(colours.Contains("green"));
        Console.WriteLine(colours.Contains("pink"));
        Console.WriteLine(colours.Contains("Green"));
        Console.WriteLine(colours.Count);
    }
}

How It Works

  1. Found. "green" is stored, so the first call prints True.
  2. Missing. "pink" was never added, so the answer is False. A missing item is a normal answer, not an error.
  3. Case matters here. With the default comparer "Green" (capital G) is a different string from "green", so this one is False too.
  4. No side effects. Looking things up changes nothing, so Count is still 3.

Example 2 — Contains With a Case-Insensitive Set

Create the set with StringComparer.OrdinalIgnoreCase and look up the same name in different spellings. Also see how null behaves.

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

class Program {
    static void Main() {
        HashSet<string> names = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Asha", "Ravi" };

        Console.WriteLine(names.Contains("asha"));
        Console.WriteLine(names.Contains("RAVI"));
        Console.WriteLine(names.Contains("Meena"));

        Console.WriteLine(names.Contains(null));
        names.Add(null);
        Console.WriteLine(names.Contains(null));
        Console.WriteLine(names.Count);
    }
}

How It Works

  1. Comparer at creation. The comparer is chosen when the set is built. A collection initializer in braces can follow the constructor call to fill it.
  2. Case ignored. "asha" and "RAVI" match the stored "Asha" and "Ravi", so both print True. "Meena" is a different name and prints False.
  3. Null is a normal item. At first Contains(null) is False, since no null was added. After Add(null) it is True.
  4. Three items. The two names plus the one null make Count 3.

Example 3 — Check Users Against an Allow-List

Keep the allowed user names in a set and test a few inputs. This is a common real use for Contains.

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

class Program {
    static void Main() {
        HashSet<string> allowed = new HashSet<string> { "admin", "user" };
        string[] inputs = { "admin", "guest", "root", "user" };

        int denied = 0;
        foreach (string name in inputs) {
            if (allowed.Contains(name)) {
                Console.WriteLine(name + ": allowed");
            } else {
                Console.WriteLine(name + ": denied");
                denied++;
            }
        }

        Console.WriteLine("Denied count: " + denied);
    }
}

How It Works

  1. Set as a filter. allowed holds only the two names that may pass. Each name is stored once, which is what an allow-list needs.
  2. Array keeps the order. The loop reads inputs, an array, so the lines always print in the same order. The set is only used to answer questions.
  3. Two branches. "admin" and "user" are in the set and are allowed. "guest" and "root" are not, so they reach the else branch.
  4. Counting denials. The variable denied goes up in the else branch only, so the final line reports 2.

Frequently Asked Questions

It returns true if the set holds an equal item and false if it does not. It does not change the set.
Usually yes for large collections. HashSet.Contains takes about the same short time on average no matter how many items there are, while List.Contains checks items one by one.
Create the set with a comparer: new HashSet<string>(StringComparer.OrdinalIgnoreCase). Then Contains, Add, and Remove all ignore case.
Yes, for reference types. Contains(null) is true only after you have added null to the set.
For your own classes the set uses Equals and GetHashCode. If you did not override them, two objects with the same data are different items. Override both so equal data means equal objects.

Next: CopyTo()

Copy the items of a HashSet into an array; the order of the copied items is not promised.

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.

9 people found this page helpful