C# HashSet TryGetValue() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In C#, HashSet.TryGetValue(equalValue, out actualValue) looks for an item that is equal to the one you pass, and gives you back the item the set really stores. This matters because "equal" does not always mean "identical".

Picture a set that ignores letter case. It holds "Asha". You search with "ASHA". Contains() only says true. TryGetValue says true and hands you "Asha", the spelling that was stored. When nothing matches, it returns false and actualValue is the default value of the type (null for a string).

This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.TryGetValue(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order. TryGetValue exists in .NET Core 2.0 and later, and in .NET Framework 4.7.2 and later. Very old projects may not have it.

Syntax

Pass the probe item, and declare an out variable to receive the stored item.

C#
HashSet<string> names = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Asha", "Ravi" };

bool found = names.TryGetValue("ASHA", out string actual);
// found is true, actual is "Asha" (the stored spelling)

bool missing = names.TryGetValue("Zed", out string none);
// missing is false, none is null
CallWhat it does
names.TryGetValue("ASHA", out string actual)Returns true and sets actual to the stored "Asha".
names.TryGetValue("Zed", out string none)Returns false and sets none to default (null for strings).
names.TryGetValue(x, out _)The underscore throws the value away when you only care about true or false. Then Contains is simpler.

TryGetValue does one lookup, uses the set's comparer, and never throws for a missing item. A HashSet has no indexer, so this is the only way to get the stored copy of an item.

Library declarations
C#
public bool TryGetValue(T equalValue, out T actualValue);

Parameters

ParameterDescription
equalValueRequired. The item to search for. It only has to be equal to a stored item, as decided by the set's comparer.
actualValueOutput. If found, the item exactly as it is stored in the set. If not found, default(T).

Return Value

Return ValueDescription
booltrue if an equal item was found. false if not (and actualValue is default).

C# Examples

Example 1 — Get the Stored Spelling

Build a case-insensitive set, probe it with capital letters, and compare the probe with what the set returns.

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

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

        string probe = "ASHA";
        bool found = names.TryGetValue(probe, out string actual);

        Console.WriteLine(found);
        Console.WriteLine(actual);
        Console.WriteLine(actual == probe);

        bool missing = names.TryGetValue("Zed", out string none);
        Console.WriteLine(missing);
        Console.WriteLine(none == null);
    }
}

How It Works

  1. Equal, not identical. With OrdinalIgnoreCase the probe "ASHA" counts as equal to the stored "Asha", so found is True.
  2. The stored copy comes back. actual is "Asha", the spelling kept in the set, not the capital letters you typed.
  3. Normal string comparison. actual == probe uses exact, case-sensitive comparison, so it prints False.
  4. No match. For "Zed" the call returns False and none is null, so none == null is True.

Example 2 — Turn User Input Into the Official Spelling

Use TryGetValue to convert sloppy input like RAVI into the official stored name.

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

class Program {
    static void Main() {
        HashSet<string> official = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Asha", "Ravi", "Meena" };
        string[] typed = { "RAVI", "meena", "Zed" };

        foreach (string text in typed) {
            if (official.TryGetValue(text, out string stored)) {
                Console.WriteLine(text + " -> " + stored);
            } else {
                Console.WriteLine("Unknown: " + text);
            }
        }
    }
}

How It Works

  1. One list of official names. The set stores each name once, in its proper capital-letter style.
  2. Lookup in the condition. TryGetValue sits in the if, so the out variable stored is ready to use inside that branch.
  3. Two matches. "RAVI" and "meena" ignore case and map to "Ravi" and "Meena". That is the clean-up the method makes possible.
  4. Unknown input. "Zed" is not in the set, so the else branch prints a message. The typed array keeps the output order fixed.

Example 3 — Find the Stored Object by Its Id

Make a small class that is equal when the Id matches. Probe with a blank object and receive the real one back.

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

class Product {
    public int Id;
    public string Name;

    public override bool Equals(object obj) {
        Product other = obj as Product;
        return other != null && other.Id == Id;
    }

    public override int GetHashCode() {
        return Id;
    }
}

class Program {
    static void Main() {
        HashSet<Product> catalog = new HashSet<Product> {
            new Product { Id = 1, Name = "Pen" },
            new Product { Id = 2, Name = "Book" }
        };

        Product probe = new Product { Id = 2, Name = "?" };

        if (catalog.TryGetValue(probe, out Product stored)) {
            Console.WriteLine(stored.Name);
            Console.WriteLine(ReferenceEquals(stored, probe));
        }
    }
}

How It Works

  1. Equality by Id. Equals and GetHashCode both use only Id, so two products with Id 2 are "equal" even when the names differ.
  2. Probe with a stub. probe has the right Id but a useless name, "?". It is enough to find the match.
  3. Real object returned. stored is the product the set already holds, so stored.Name prints Book. Contains could not give you this.
  4. Different objects. ReferenceEquals is False because stored and probe are two separate objects that happen to be equal.

Frequently Asked Questions

It searches for an item equal to the one you pass and returns true or false. When it succeeds, the out parameter holds the item exactly as the set stores it.
Contains returns only true or false. TryGetValue also gives you the stored item, which matters when equal items are not identical, such as different letter case or different objects with the same Id.
It is in .NET Core 2.0 and later and in .NET Framework 4.7.2 and later. In older projects you do not have it, so you would need another approach such as a Dictionary.
It is default of the item type: null for strings and other reference types, 0 for int, and false for bool.
No. A HashSet has no indexer and no order, so set[0] does not exist. Use TryGetValue to get the stored copy of an item you can describe.

Next: UnionWith()

Add every item of another collection into the HashSet (union); the set is changed in place.

UnionWith() 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.

7 people found this page helpful