How to use hashtable in c# with example

How to use hashtable in c# with example



How to Use Hashtable in C# with Example

The Hashtable class in C# is a non-generic collection that stores key-value pairs as objects. This structure allows quick lookups and management of data. While newer collections like Dictionary<TKey, TValue> are often preferred, Hashtable remains useful in certain scenarios. This article will guide you through using Hashtable in C#, with practical examples.

Key Features of Hashtable

  • Key-Value Pairs: Stores keys and values as objects.
  • Unique Keys: Keys must be unique within the collection.
  • Null Keys/Values: Allows null keys and values.
  • Thread Safety: Provides limited thread safety through SyncRoot.

Example: Creating and Using a Hashtable

Basic Operations

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

 

using System;
using System.Collections;

public class HashtableExample
{
    public static void Main()
    {
        // Create a hashtable and add key-value pairs
        Hashtable phoneBook = new Hashtable
        {
            { "Alice", "+1-202-555-0112" },
            { "Bob", "+1-202-555-0158" },
            { "Charlie", "+1-202-555-0199" }
        };

        // Add a new key-value pair
        phoneBook["Diana"] = "+1-202-555-0177";

        // Access a value using the indexer syntax
        Console.WriteLine($"Alice's number: {phoneBook["Alice"]}");

        // Check if a key exists using ContainsKey
        if (phoneBook.ContainsKey("Bob"))
        {
            Console.WriteLine($"Bob's number: {phoneBook["Bob"]}");
        }

        // Remove a key-value pair by key
        phoneBook.Remove("Charlie");

        // Iterate through all key-value pairs using a foreach loop
        Console.WriteLine("\nRemaining contacts:");
        foreach (DictionaryEntry entry in phoneBook)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
}

Best Practices for Using Hashtable

  • Null Handling: Handle null keys/values gracefully to avoid errors.
  • Thread Safety: Use SyncRoot or a synchronized wrapper if accessing from multiple threads.
  • Type Safety: Ensure proper type casting to prevent runtime exceptions.

Common Methods

  1. Add: Adds a new key-value pair using Add(key, value).
  2. Remove: Removes a key-value pair based on the key.
  3. ContainsKey: Checks for the existence of a key.
  4. Clear: Removes all key-value pairs.

Conclusion

Hashtable in C# is a versatile collection for managing key-value pairs, especially in legacy or mixed-data scenarios. By understanding its features and following best practices, you can make the most of Hashtable in your projects.


 


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

Popular Posts

c# hashmap

4 months ago
c# hashmap

What is a Delegate in C#?

5 months ago
What is a Delegate in C#?

c# sortedset performance

4 months ago
c# sortedset performance

While in c# example for loop

5 months ago
While in c# example for loop

Tags