C#:C# Dictionary<TKey, TValue>: Hash Table Operations
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:

ParameterTypeDescription
TryGetValueMethodSafely retrieves value without throwing KeyNotFoundException.

Ready-to-Run Code Example

Executable in Compilra

Run 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); // Safe

Related C# Tutorials & Compiler

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler