Hashtable in c# with example

Hashtable in c# with example
In this article [Show more]

    Hashtable in C# with Example

    In C#, the Hashtable class is a collection that stores key-value pairs. It allows efficient access and management of data using keys. Although it's been largely replaced by the generic Dictionary<TKey, TValue>, Hashtable is still relevant in certain scenarios. This article provides an overview of Hashtable and a practical example of its usage.

    Features of Hashtable

    • Key-Value Pair Storage: Stores objects as key-value pairs.
    • Non-Generic: Keys and values are stored as objects.
    • Null Handling: Supports null values and keys.
    • Thread Safety: Limited support for thread safety through the SyncRoot property.
    • Boxing/Unboxing: Requires boxing/unboxing for value types.

    Example: Creating and Using a Hashtable

    Basic Operations

    Here's how to create a Hashtable, add key-value pairs, and read data:

     

    using System;
    using System.Collections;
    
    public class HashtableExample
    {
        public static void Main()
        {
            // Create a new Hashtable
            Hashtable table = new Hashtable
            {
                { "USA", "Washington, D.C." },
                { "UK", "London" },
                { "France", "Paris" },
                { "Germany", "Berlin" }
            };
    
            // Add a new key-value pair
            table["Japan"] = "Tokyo";
    
            // Access values using keys
            Console.WriteLine($"Capital of USA: {table["USA"]}");
            Console.WriteLine($"Capital of Japan: {table["Japan"]}");
    
            // Check if a key exists
            string country = "Italy";
            if (!table.ContainsKey(country))
            {
                Console.WriteLine($"Key '{country}' not found.");
            }
    
            // Remove a key-value pair
            table.Remove("France");
    
            // Iterate through the hashtable using a foreach loop
            Console.WriteLine("\nRemaining elements in the hashtable:");
            foreach (DictionaryEntry entry in table)
            {
                Console.WriteLine($"{entry.Key}: {entry.Value}");
            }
        }
    }
    

    Key Operations

    1. Add: Adds a new key-value pair using Add(key, value).
    2. Remove: Removes a key-value pair using Remove(key).
    3. ContainsKey: Checks if a specific key exists.
    4. Count: Returns the number of key-value pairs.
    5. Clear: Removes all key-value pairs from the hashtable.

    Best Practices

    • Avoid Null Keys: Although Hashtable allows null keys, it's better to use non-null keys for consistent data management.
    • Type Safety: Handle value types carefully to avoid errors due to boxing/unboxing.
    • Thread Safety: Use SyncRoot or a synchronized wrapper for multi-threaded scenarios.

    Conclusion

    Hashtable in C# is a versatile collection for managing key-value pairs, especially when you require non-generic data handling or compatibility with legacy code. By understanding its features, operations, and best practices, you can leverage it effectively in your applications

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments