hashtable vs dictionary in c#

hashtable vs dictionary in c#
In this article [Show more]

    Hashtable vs. Dictionary in C#

    In C#, both Hashtable and Dictionary<TKey, TValue> are collections that store key-value pairs. While they have similar functions, there are important differences between the two. This article will compare Hashtable and Dictionary, explaining their key features, differences, and use cases to help you choose the right one for your application.

    Hashtable

    • Non-Generic: Hashtable is a non-generic collection available since .NET Framework 1.0.
    • Key-Value Pair: Stores keys and values as objects.
    • Thread Safety: Provides limited thread safety through SyncRoot.
    • Null Handling: Allows null keys and values.
    • Boxing/Unboxing: Requires boxing/unboxing for value types, which may affect performance.

    Example: Using Hashtable

     

    using System;
    using System.Collections;
    
    public class HashtableExample
    {
        public static void Main()
        {
            // Create a new Hashtable
            Hashtable table = new Hashtable
            {
                { "Alice", 30 },
                { "Bob", 35 },
                { "Charlie", 40 }
            };
    
            // Access values using keys
            Console.WriteLine($"Alice's age: {table["Alice"]}");
            Console.WriteLine($"Bob's age: {table["Bob"]}");
    
            // Iterate through the key-value pairs
            Console.WriteLine("\nAll elements in the hashtable:");
            foreach (DictionaryEntry entry in table)
            {
                Console.WriteLine($"{entry.Key}: {entry.Value}");
            }
        }
    }
    

    Dictionary

    • Generic: Dictionary<TKey, TValue> is a generic collection introduced in .NET 2.0.
    • Key-Value Pair: Strongly typed, requiring a specific key and value type.
    • Thread Safety: Not inherently thread-safe.
    • Null Handling: Allows null values but not null keys.
    • Performance: Generally faster due to no boxing/unboxing.

    Example: Using Dictionary

     

    using System;
    using System.Collections.Generic;
    
    public class DictionaryExample
    {
        public static void Main()
        {
            // Create a new dictionary with string keys and integer values
            Dictionary<string, int> ages = new Dictionary<string, int>
            {
                { "Alice", 30 },
                { "Bob", 35 },
                { "Charlie", 40 }
            };
    
            // Access values using keys
            Console.WriteLine($"Alice's age: {ages["Alice"]}");
            Console.WriteLine($"Bob's age: {ages["Bob"]}");
    
            // Iterate through the key-value pairs
            Console.WriteLine("\nAll elements in the dictionary:");
            foreach (KeyValuePair<string, int> kv in ages)
            {
                Console.WriteLine($"{kv.Key}: {kv.Value}");
            }
        }
    }
    

    Key Differences Between Hashtable and Dictionary

    Type Safety:

    • Hashtable is non-generic and stores everything as objects.
    • Dictionary is generic and strongly typed.

    Null Handling:

    • Hashtable allows null keys and values.
    • Dictionary does not allow null keys but supports null values.

    Performance:

    • Hashtable incurs performance costs due to boxing/unboxing.
    • Dictionary is generally more efficient due to type safety.

    Thread Safety:

    • Hashtable provides limited thread safety using SyncRoot.
    • Dictionary is not thread-safe but can use ConcurrentDictionary.

    Conclusion

    While both Hashtable and Dictionary offer key-value pair storage, Dictionary is preferred for most modern applications due to its type safety and performance. Hashtable can still be useful for legacy applications or where null keys are needed.

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments