c# hashmap

c# hashmap


C# HashMap

In C#, there isn't a specific data structure called a "HashMap," but the closest equivalent is the Dictionary<TKey, TValue> class, which provides a way to store key-value pairs with efficient lookups using hashing. This article explores how to use a Dictionary<TKey, TValue> as a HashMap in C#, its key features, and practical examples.

Features of Dictionary<TKey, TValue>

  • Key-Value Pairs: Each key maps to a specific value.
  • Unique Keys: Each key must be unique, preventing duplicates.
  • Efficient Lookup: Provides fast access using hashing.
  • Type Safety: Generic, providing compile-time type checking.

Example: Creating and Using a Dictionary

Basic Operations

This example demonstrates how to create a Dictionary<TKey, TValue>, add key-value pairs, and access values efficiently:

 

using System;
using System.Collections.Generic;

public class DictionaryExample
{
    public static void Main()
    {
        // Create a dictionary with string keys and integer values
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Alice", 25 },
            { "Bob", 30 },
            { "Charlie", 35 }
        };

        // Add a new key-value pair
        ages["Diana"] = 28;

        // Retrieve values using indexer syntax
        Console.WriteLine($"Alice's age: {ages["Alice"]}");
        Console.WriteLine($"Diana's age: {ages["Diana"]}");

        // Safely retrieve a value using TryGetValue
        if (ages.TryGetValue("Charlie", out int charlieAge))
        {
            Console.WriteLine($"Charlie's age: {charlieAge}");
        }
        else
        {
            Console.WriteLine("Key not found.");
        }

        // Iterate through all key-value pairs
        Console.WriteLine("\nList of all ages:");
        foreach (KeyValuePair<string, int> kv in ages)
        {
            Console.WriteLine($"{kv.Key}: {kv.Value}");
        }
    }
}

Best Practices for Working with Dictionary

  • Capacity Management: Set an appropriate initial capacity to minimize resizing overhead.
  • Keys: Ensure keys implement consistent hash codes for reliable behavior.
  • TryGetValue: Prefer TryGetValue to safely access values without exceptions.

Conclusion

In C#, the Dictionary<TKey, TValue> class serves as an efficient and type-safe HashMap. By understanding its features and operations, you can effectively manage key-value pairs in your applications.


 

Leave a reply Your email address will not be published. Required fields are marked*