C#•Dictionaries
C# Dictionary<TKey, TValue>: Hash Table Operations
Learn high-performance hash lookups in C# and safe lookup patterns with TryGetValue.
Syntax
var dict = new Dictionary<string, int>();
dict["key"] = 100;
dict.TryGetValue("key", out int val);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| TryGetValue | Method | Safely retrieves value without throwing KeyNotFoundException. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
var portRegistry = new Dictionary<string, int> {
["HTTP"] = 80,
["HTTPS"] = 443,
["SSH"] = 22
};
// Adding entries
portRegistry["REDIS"] = 6379;
// Safe lookup with TryGetValue
string queryProtocol = "HTTPS";
if (portRegistry.TryGetValue(queryProtocol, out int port)) {
Console.WriteLine($"{queryProtocol} is bound to port {port}");
}
Console.WriteLine("\nAll Registered Ports:");
foreach (var kvp in portRegistry) {
Console.WriteLine($" {kvp.Key} -> {kvp.Value}");
}
}
}Expected Output:
HTTPS is bound to port 443 All Registered Ports: HTTP -> 80 HTTPS -> 443 SSH -> 22 REDIS -> 6379
How It Works: Step-by-Step
- Lines 6-10: Initializes Dictionary with C# indexer initializer syntax.
- Lines 17-19: TryGetValue retrieves port safely without throwing.
Key Concepts
- Dictionary provides O(1) average lookup and insertion time.
- Accessing dict[missingKey] throws KeyNotFoundException; use TryGetValue or ContainsKey.
Common Mistake: Reading missing key with indexer dict[missingKey]
Reading a nonexistent key throws KeyNotFoundException. Use TryGetValue instead.
❌ Incorrect
int p = portRegistry["UNKNOWN"]; // Throws KeyNotFoundException!
✅ Correct
portRegistry.TryGetValue("UNKNOWN", out int p); // SafeRelated C# Tutorials & Compiler
C# List<T> and LINQ Queries: Where, Select, and Aggregate
Master dynamic List<T> collections and powerful LINQ queries (Where, Select, Sum).
C# HashSet<T> and ValueTuples (Multiple Return Values)
Deduplicate data with HashSet<T> and return multiple values using lightweight ValueTuples.
C# String Methods, String Interpolation, and StringBuilder
Master text manipulation with string methods, raw string literals, and StringBuilder.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.