Skip to content
Guest
Learn C# · Course Syllabus Show lessons
Modern .NET APIs · 8 min read · Beginner

Dictionaries, HashSets & TryGetValue

Avoid KeyNotFoundException with TryGetValue() and deduplicate collections fast with HashSet<T>.

What you'll learn

  • Perform safe O(1) lookups with Dictionary.TryGetValue(key, out var val)
  • Use HashSet<T> for fast membership checks and deduplication
  • Initialize collections concisely with C# 12 collection expressions ([...])

Accessing dict["missing"] in C# throws a KeyNotFoundException. The idiomatic, single-lookup pattern is if (dict.TryGetValue(key, out var value)), which checks existence and extracts the value in one hash lookup.

Fill-in-the-Blank Exercise

Safe Dictionary Lookup

Look up 'csharp' safely using TryGetValue and an out variable.

if (scores.("csharp",  int val))
{
  Console.WriteLine(val);
}

Live Code Lab

C#DictionariesDemo.cs
Expected OutputClick “Run Live” to compile with Mono C#
C# score: 92
Unique tags: 3

Check Your Understanding

Score: 0 / 1

1. Why is TryGetValue(key, out var val) preferred over ContainsKey(key) + dict[key]?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind