Skip to content
Learn Netverks

Lesson

Step 19/36 53% through track

dictionaries-csharp

Dictionaries

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Dictionaries: the syntax, patterns, and safety habits you need before advancing in C#.

Teams still ship Dictionaries in C# codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Dictionaries in contexts like: .NET services, Unity games, and Windows-centric tooling.

Write C# with Console.WriteLine (top-level or Program), click Run on server—the dev runner uses dotnet build/run on a temp net8 project (requires .NET SDK; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Dictionary<TKey, TValue> maps keys to values with fast lookup—like HashMap in Java or dicts in Python. HashSet<T> stores unique elements with set operations.

Dictionary usage

var counts = new Dictionary<string, int>();
counts["apple"] = 3;
if (counts.TryGetValue("apple", out int n)) {
    Console.WriteLine(n);
}

Prefer TryGetValue over double indexing when the key might be missing—avoids two hash lookups.

HashSet

var tags = new HashSet<string> { "csharp", "dotnet" };
tags.Add("csharp");  // ignored duplicate

Important interview questions and answers

  1. Q: Dictionary vs List?
    A: Dictionary keyed lookup O(1) average; List is ordered by index—scan for keys is O(n).
  2. Q: HashSet vs List for uniqueness?
    A: HashSet enforces uniqueness with hash-based membership tests.

Self-check

  1. What method safely reads a missing dictionary key?
  2. Does HashSet allow duplicates?

Pitfall: dict[key] throws if the key is missing—use TryGetValue or ContainsKey when insertion side effects are unwanted.

Interview prep

Dictionary vs Hashtable?

Dictionary<TKey,TValue> is generic and type-safe; legacy Hashtable boxes keys and values as object.

TryGetValue vs indexer?

TryGetValue avoids exceptions and unwanted inserts; dict[key] throws when the key is missing.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • TryGetValue why?
  • Hash collision?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump