C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

C# Hash Table with Examples

Hashtable is a collection class that provides a mapping between keys and values. It is built on a hashing method that associates keys with certain locations within an internal data structure known as a bucket. There may be one or more key-value pairs in each bucket.

Key Characteristics of Hash Table

Unique keys: Hashtable enforces key uniqueness, meaning each key can only exist once within the collection.

Effective lookup: The hashing algorithm is used to quickly access the corresponding bucket when retrieving a value from the Hashtable based on a key.

Automatic resizing: As components are added or removed, the internal structure of the Hashtable dynamically adjusts to maintain optimal speed and memory usage.

Enumeration: Hashtable offers attributes and methods for enumerating through its components, enabling easy iteration and processing.

Creating and Initializing a HashTable

Syntax for creating a new Hashtable object:

Hashtable hashtable = new Hashtable();

Examples of different ways to initialize a Hashtable with key-value pairs:

1. Initializing with individual Add() method calls:

Hashtable hashtable = new Hashtable();

hashtable.Add("Key1", "Value1");

hashtable.Add("Key2", "Value2");

hashtable.Add("Key3", "Value3");

2. Initializing with object initializer syntax:

Hashtable hashtable = new Hashtable()

{

    { "Key1", "Value1" },

    { "Key2", "Value2" },

    { "Key3", "Value3" }

};

3. Initializing with a collection of key-value pairs:

var keyValuePairs = new Dictionary<string, string>

{

    { "Key1", "Value1" },

    { "Key2", "Value2" },

    { "Key3", "Value3" }

};

Hashtable hashtable = new Hashtable(keyValuePairs);

Fixing duplicate values and keys:

  • Duplicate keys are not permitted in hashtables. It will throw an exception if you attempt to add an already present key.
  • A hashtable allows for the duplication of values. Multiple entries with the same value linked to various keys are possible.

Example of managing duplicate keys:

using System;

using System.Collections;

class Program

{

    static void Main()

    {

        Hashtable hashtable = new Hashtable();

        hashtable.Add("Name", "Vardhan");

        hashtable.Add("Number", "41");

        hashtable.Add("Key", "Vardhan"); // Duplicate value

        // Retrieving all keys associated with the duplicate value

        var keysWithDuplicateValue = new ArrayList();

        foreach (DictionaryEntry entry in Hashtable)

        {

            if (entry.Value.Equals("Vardhan"))

            {

                keysWithDuplicateValue.Add(entry.Key);

            }

        }

        Console.WriteLine("Keys with duplicate value 'Vardhan':");

        foreach (var key in keysWithDuplicateValue)

        {

            Console.WriteLine(key);

        }

    }

}

Output:

Adding and Removing Elements

Add() method can be used to add elements to the Hashtable.

using System;

using System.Collections;

class Program

{

    static void Main()

    {

        Hashtable hashtable = new Hashtable();

        // Adding elements using the Add() method

        hashtable.Add("Hobby", "Television");

        hashtable.Add("Name", "Johnson");

        hashtable.Add("Age", "40");

        // Displaying the elements in the Hashtable

        foreach (DictionaryEntry entry in Hashtable)

        {

            Console.WriteLine(entry.Key + ": " + entry.Value);

        }

    }

}

Output:

Note: The Add() method throws an exception if you try to add an element with a duplicate key. To handle this, you can use the indexer to update the value for an existing key or the ContainsKey() method to check if the key already exists before adding a new element.

The following is an example demonstrating the use of the ContainsKey() method

using System;

using System.Collections;

class Program

{

    static void Main()

    {

        Hashtable hashtable = new Hashtable();

        // Adding elements using the indexer to update existing keys

        hashtable["Name1"] = "Sai";

        hashtable["Name2"] = "Vardhan";

        hashtable["Name3"] = "Rathnam";

        // Updating the value for an existing key

        hashtable["Name2"] = "Venkat";

        // Checking if the key exists before adding a new element

        if (!hashtable.ContainsKey("Name3"))

        {

            hashtable.Add("Name3", "Lasya");

        }

        // Displaying the elements in the Hashtable

        foreach (DictionaryEntry entry in Hashtable)

        {

            Console.WriteLine(entry.Key + ": " + entry.Value);

        }

    }

}

Output:

Removing elements using the Remove() method:

using System;

using System.Collections;

class Program

{

    static void Main()

    {

                Hashtable hashtable = new Hashtable();

       hashtable["Name1"] = "Sai";

        hashtable["Name2"] = "Vardhan";

        hashtable["Name3"] = "Rathnam";

// Removing an element by key

hashtable.Remove("Name1");

hashtable.Remove("Name2");

        // Displaying the elements in the Hashtable

        foreach (DictionaryEntry entry in Hashtable)

        {

            Console.WriteLine(entry.Key + ": " + entry.Value);

        }

    }

}

Output:

Name3: Rathnam

Clearing all elements from the Hashtable:

The clear() method is used to clear all the elements from the Hashtable.

using System;

using System.Collections;

class Program

{

    static void Main()

    {

        Hashtable hashtable = new Hashtable();

        hashtable["Name1"] = "Sai";

        hashtable["Name2"] = "Vardhan";

        hashtable["Name3"] = "Rathnam";

        // Clearing all elements

        hashtable.Clear();

        // After clearing, the Hashtable will be empty

        Console.WriteLine("Count: " + hashtable.Count);

    }

}

Output:

Retrieving values based on keys

The Hashtable's values can be accessed via their respective keys because of the indexer. The value linked to the supplied key is retrieved using the syntax hashtable["Key"]. It would be best to cast the received value to the correct type because Hashtable holds objects.

using System;

using System.Collections;

class Program

{

    static void Main()

    {

        Hashtable hashtable = new Hashtable();

        hashtable["Name1"] = "Raja";

        hashtable["Name2"] = "Vardhan";

        hashtable["Name3"] = "Rathnam";

        string value1 = (string)hashtable["Name1"];

        string value2 = (string)hashtable["Name2"];

        Console.WriteLine(value1); 

        Console.WriteLine(value2); 

    }

}

Output:

Checking if a key exists in the Hashtable

The Hashtable class contains the methods ContainsKey(key) and ContainsValue(value) to check for the existence of a key. If the Hashtable contains the supplied key or value, the functions ContainsKey(key) and ContainsValue(value) return true.

using System;

using System.Collections;

class Program

{

    static void Main()

    {

        Hashtable hashtable = new Hashtable();

        hashtable["Name1"] = "Raja";

        hashtable["Name2"] = "Vardhan";

        hashtable["Name3"] = "Rathnam";

        bool containsKey = hashtable.ContainsKey("Name1");

        bool containsValue = hashtable.ContainsValue("Vardhan");

        Console.WriteLine(containsKey);

        Console.WriteLine(containsValue);

    }

}

Output:

Modifying the values for existing keys

To update the value for an existing key in the Hashtable, assign the new value to the corresponding key using the indexer. The line hashtable["Name1"] = "Vardhan" updates the value associated with the key "Name1" to "Vardhan". This operation replaces the existing value with the new one.

using System;

using System.Collections;

class Program

{

    static void Main()

    {

        Hashtable hashtable = new Hashtable();

        hashtable["Name1"] = "Raja";

        hashtable["Name3"] = "Rathnam";

        // Update the value for an existing key

        hashtable["Name1"] = "Vardhan";

        string updatedValue = (string)hashtable["Name1"];

        Console.WriteLine(updatedValue);

    }

}

Output:

It's possible to run into exceptions when accessing elements in a hashtable. A KeyNotFoundException will be raised if you use the indexer to try to access a key that doesn't exist. Use a try-catch block to capture the exception and treat the problem properly to handle this.

using System;

using System.Collections;

using System.Collections.Generic;

class Program

{

    static void Main()

    {

        Hashtable hashtable = new Hashtable();

        hashtable.Add("Fruit", "Mango");

        try

        {

            if (hashtable.ContainsKey("Fruit"))

            {

                hashtable["Fruit"] = "Orange";

                Console.WriteLine(hashtable["Fruit"]);

                Console.WriteLine("Value updated successfully.");

            }

            else

            {

                Console.WriteLine("Key not found.");

            }

        }

        catch (KeyNotFoundException)

        {

            Console.WriteLine("Key not found.");

        }

    }

}

Output:

A try-catch block is used in the provided code to catch the KeyNotFoundException and show a customised message informing the user that it could not be located. Additionally, by first determining whether the key exists using the ContainsKey(key) method, it illustrates a secure approach to alter the value of an existing key.

Time Complexity:

Addition (Add): Adding an element to a hashtable is typically thought to have an O(1) time complexity. The temporal complexity can, however, decrease to O(n) in the worst-case situation where there are several hash collisions, where n is the total number of elements in the Hashtable.

Removal (Remove): It is generally accepted that the temporal complexity of deleting an element from a hashtable is O(1). Similar to addition, the time complexity can be O(n) in the worst-case situation with several hash collisions.

Retrieval (Access): On average, it takes O(1) of time to access an entry in a hashtable using its key. Again, hash collisions might make it O(n) in the worst-case scenario.

Memory Usage:

The hashtable stores key-value pairs in memory. The amount of memory used is inversely correlated with the number of elements kept in the Hashtable. Each key-value pair uses RAM for the internal data structures utilised by the Hashtable and additional RAM for storing the key and value objects.

Applications of HashTable

1. Counting Word Frequencies

In this example, a Hashtable is used to count the frequencies of words in an array. The keys of the Hashtable represent the words, and the values represent their frequencies.

using System;

using System.Collections;

class Program

{

    static void Main(string[] args)

    {

        Hashtable wordFrequencies = new Hashtable();

        string[] words = { "apple", "banana", "apple", "cherry", "banana", "apple" };

        foreach (string word in words)

        {

            if (wordFrequencies.ContainsKey(word))

            {

                wordFrequencies[word] = (int)wordFrequencies[word] + 1;

            }

            else

            {

                wordFrequencies[word] = 1;

            }

        }

        foreach (DictionaryEntry entry in wordFrequencies)

        {

            Console.WriteLine($"{entry.Key}: {entry.Value}");

        }

    }

}

Output:

2. Caching Results

In this example, previously calculated Fibonacci numbers are stored in a Hashtable cache. The function determines whether a Fibonacci number exists in the cache before computing it. If yes, it avoids unnecessary calculations by retrieving the value from the cache.

using System;

using System.Collections;

class Program

{

    static Hashtable cache = new Hashtable();

    static int CalculateFibonacci(int n)

    {

        if (cache.ContainsKey(n))

        {

            return (int)cache[n];

        }

        int result;

        if (n <= 1)

        {

            result = n;

        }

        else

        {

            result = CalculateFibonacci(n - 1) + CalculateFibonacci(n - 2);

        }

        cache[n] = result;

        return result;

    }

    static void Main(string[] args)

    {

        int n = 10;

        int fibonacciNumber = CalculateFibonacci(n);

        Console.WriteLine($"The Fibonacci number at index {n} is {fibonacciNumber}");

    }

}

Output:

← Prev Next →