Hybriddictionary Class In C#

The HybridDictionary class in the "System.Collections.Specialized" namespace in C# provides a hybrid data structure that combines the features of a list and a dictionary.

The HybridDictionary class is a part of the .NET Framework and provides a flexible data structure for storing key-value pairs. This data structure is known as a hybrid because it alternates internally between a dictionary-based and a list-based implementation based on the number of elements in the collection.

HybridDictionary makes an effort to maximize its hashtable . The data structures hash tables and linked lists are implemented in hashtable. Implementing IDictionary uses a Hashtable for large collections and a ListDictionary for small collections.

Key Features of HybridDictionary:

There are several key features of the HybridDictionary in C#. Some key feature are as follows:

  1. Dynamic Behavior

The HybridDictionary stores key-value pairs in a basic list for several elements.

As the collection grows, it automatically switches to a hash table-based dictionary to optimize performance.

  1. Pairs of Key-Value

It allows us to use key-value pairs like a regular dictionary to store and retrieve data.

  1. Order Maintenance

Unlike traditional dictionaries, the HybridDictionary maintains the order of elements based on their insertion order, making it suitable for scenarios where the order of items matters.

  1. Efficient for Small Collections

The list-based representation is more memory-efficient for small collections, avoiding the overhead associated with hashtables.

  1. Hashtable for Large Collections

As the number of elements in the collection grows, the HybridDictionary switches to using a hashtable, providing faster lookup times for larger data sets.

Use Cases of HybridDictionary:

There are several use cases of the HybridDictionary in C#. Some use cases are as follows:

  1. Dynamic Data Sets

It is suitable for scenarios where the collection size is not known in advance and can vary.

  1. Balancing Memory and Performance

It is efficient for scenarios where a balance between memory usage and lookup performance is crucial.

  1. Combination of List and Hashtable

It combines the benefits of a simple list and a hashtable, adapting to the characteristics of the data set.

Properties of the HybridDictionary class

There are several properties of the HybridDictionary in C#. Some properties are as follows:

1. Count

It gets the number of key-value pairs that the HybridDictionary contains.

The number of key-value pairs in the Dictionary may be obtained using the Count property of the HybridDictionary class in C#. The count of elements in the HybridDictionary is returned as an integer . This property is part of the standard set of properties that provides information about the state of the Dictionary.

Syntax:

It has the following syntax:

Example

int count = hybridDictionary.Count;

Example:

Let us take an example to illustrate the Count property of HybridDictionary in C#.

Example

using System;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dict.Add("Mango", 1);
        hybrid_Dict.Add("Banana", 2);
        hybrid_Dict.Add("Orange", 3);
        hybrid_Dict.Add("Grapes", 4);
        // Accessing the Count property
        int number_Of_Elements = hybrid_Dict.Count;
        Console.WriteLine("The number of elements in the HybridDictionary is: " + number_Of_Elements);
    }
}

Output:

Output

The number of elements in the HybridDictionary is: 4

Explanation:

In this example, the number of key-value pairs in the HybridDictionary is obtained using the Count property. The numberOfElements variable will be set to 4 after adding four key-value pairs.

2. IsFixedSize

The C# HybridDictionary class has a boolean property called IsFixedSize that determines whether the HybridDictionary's size is fixed . When IsFixedSize returns true, it indicates that its size cannot be changed once the HybridDictionary has been created.

Syntax:

It has the following syntax:

Example

bool isFixedSize = hybridDictionary.IsFixedSize;

Example:

Let us take an example to illustrate the IsFixedSize property of HybridDictionary in C#.

Example

using System;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dict.Add("one", 1);
        hybrid_Dict.Add("two", 2);
        // Checking if the HybridDictionary has a fixed size
        bool isFixedSize = hybrid_Dict.IsFixedSize;
        Console.WriteLine("Is the HybridDictionary fixed size? " + isFixedSize);
        // Attempting to add a new key-value pair to a fixed-size HybridDictionary
        try
        {
            hybrid_Dict.Add("three", 3); // This will throw an exception if IsFixedSize is true
        }
        catch (NotSupportedException ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
    }
}

Output:

Output

Is the HybridDictionary fixed size? False

Explanation:

In this example, the HybridDictionary's fixed size is determined using the IsFixedSize property. Any attempt to add or remove dictionary elements will result in a NotSupportedException if the property returns true . In the example, after checking the IsFixedSize property, attempting to add a new key-value pair raises an exception.

3. IsReadOnly

The IsReadOnly property of the HybridDictionary class in C# is a boolean property that indicates whether the HybridDictionary is read-only. If IsReadOnly returns true, the HybridDictionary cannot be modified (elements cannot be added, removed, or modified).

Syntax:

It has the following syntax:

bool isReadOnly = hybridDictionary.IsReadOnly;

Example:

Let us take an example to illustrate the IsReadOnly property of HybridDictionary in C#.

Example

using System;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dict.Add("one", 1);
        hybrid_Dict.Add("two", 2);
        // Checking if the HybridDictionary is read-only
        bool isReadOnly = hybrid_Dict.IsReadOnly;
        Console.WriteLine("Is the HybridDictionary read-only? " + isReadOnly);
        // Attempting to add a new key-value pair to a read-only HybridDictionary
        try
        {
            hybrid_Dict.Add("three", 3); // This will throw an exception if IsReadOnly is true
        }
        catch (NotSupportedException ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
    }
}

Output:

Output

Is the HybridDictionary read-only? False

Explanation:

In order to determine if the HybridDictionary is read-only, the IsReadOnly property is utilized in this example. If the property returns true, attempting to modify the Dictionary (e.g., adding a new key-value pair) will result in a NotSupportedException . After verifying the IsReadOnly property, attempting to add a new key-value pair results in an exception.

4. isSynchronized

The IsSynchronized property of the HybridDictionary class in C# is a boolean property that indicates whether Access to the HybridDictionary is synchronized (thread-safe) . If IsSynchronized returns true, it means that the HybridDictionary is designed to be used safely in a multi-threaded environment, and access to its methods and properties is synchronized to ensure proper behaviour when multiple threads are accessing or modifying the Dictionary concurrently.

Syntax:

It has the following syntax:

Example

bool isSynchronized = hybridDictionary.IsSynchronized;

Example:

Let us take an example to illustrate the IsSynchronized property of HybridDictionary in C#.

Example

using System;
using System.Collections.Specialized;
using System.Threading;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dict.Add("one", 1);
        hybrid_Dict.Add("two", 2);
        // Checking if the HybridDictionary is synchronized
        bool isSynchronized = hybrid_Dict.IsSynchronized;
        Console.WriteLine("Is the HybridDictionary synchronized? " + isSynchronized);
        // Modifying the HybridDictionary in a multi-threaded scenario
        if (isSynchronized)
        {
            //Access to the HybridDictionary is synchronized
            lock (hybrid_Dict.SyncRoot)
            {
                // Perform thread-safe operations here
                hybrid_Dict.Add("three", 3);
            }
        }
        else
        {
            // If not synchronized, you need to manually synchronize Access in a multi-threaded scenario
            Console.WriteLine("Warning: The HybridDictionary is not synchronized. Manual synchronization may be required.");
        }
    }
}

Output:

Output

Is the HybridDictionary synchronized? False
Warning: The HybridDictionary is not synchronized. Manual synchronization may be required.

Explanation:

In this example, the HybridDictionary is designed for synchronised Access, and it can be determined using the IsSynchronized property. If IsSynchronized returns a true result, the Dictionary is safe to use in a multi-threaded environment. In such cases, we typically use the SyncRoot property to acquire an object that may be used as a synchronisation point for accessing or modifying the Dictionary from multiple threads.

5. Keys

A collection containing the keys stored in the HybridDictionary may be retrieved using the Keys property of the HybridDictionary class in C#. This property returns an ICollection containing all the keys, and the keys in the collection are arranged in the same order as they were added to the Dictionary.

Syntax:

It has the following syntax:

Example

ICollection keys = hybridDictionary.Keys;

Example:

Let us take an example to illustrate the Keys property of HybridDictionary in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dict.Add("Mango", 1);
        hybrid_Dict.Add("Apple", 2);
        hybrid_Dict.Add("Orange", 3);
        // Accessing the Keys property
        ICollection keys = hybrid_Dict.Keys;
        // Iterating through the keys
        Console.WriteLine("Keys in the HybridDictionary are:");
        foreach (var key in keys)
        {
            Console.WriteLine(key);
        }
    }
}

Output:

Output

Keys in the HybridDictionary are:
Mango
Apple
Orange

Explanation:

In this example, a HybridDictionary is created, populated with key-value pairs , and a collection of keys is obtained using the Keys property . Every key is printed to the console and iterated using the foreach loop .

6. Values

The Value property of the HybridDictionary class in C# is used to collect the values stored in the Dictionary. The values are returned in the order they were added to the HybridDictionary, and the collection is an ICollection with all the values. This property provides a way to iterate over the values or perform operations on the values without directly modifying the Dictionary.

Syntax:

It has the following syntax:

Example

ICollection values = hybridDictionary.Values;

Example:

Let us take an example to illustrate the Values property of HybridDictionary in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class Program
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dict.Add("Apple", 1);
        hybrid_Dict.Add("Banana", 2);
        hybrid_Dict.Add("Orang", 3);
        // Accessing the Values property
        ICollection values = hybrid_Dict.Values;
        // Iterating through the values
        Console.WriteLine("Values in the HybridDictionary are:");
        foreach (var i in values)
        {
            Console.WriteLine(i);
        }
    }
}

Output:

Output

Values in the HybridDictionary are:
1
2
3

Explanation:

In this example, the values (1, 2, 3) in the order they were added to the HybridDictionary are returned as an ICollection by hybridDict.Values . After that, the values are iterated and printed to the terminal using the foreach loop.

7. SyncRoot

In order to ensure thread safety when many threads may be accessing or modifying the Dictionary concurrently, the HybridDictionary class in C# has a SyncRoot property that may be used to acquire an object that can be used as a synchronisation point. The SyncRoot property returns an object that can be used with the lock statement to synchronize Access to the HybridDictionary.

Syntax:

It has the following syntax:

Example

object syncRoot = hybridDictionary.SyncRoot;

Example:

Let us take an example to illustrate the SyncRoot property of HybridDictionary in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dict.Add("one", 1);
        hybrid_Dict.Add("two", 2);
        hybrid_Dict.Add("three", 3);
        // Accessing the SyncRoot property
        object syncRoot = hybrid_Dict.SyncRoot;
        // Using the SyncRoot object for synchronization
        lock (syncRoot)
        {
            // Perform thread-safe operations on the HybridDictionary here
            Console.WriteLine("Accessing HybridDictionary in a thread-safe manner.");
            foreach (DictionaryEntry entry in hybrid_Dict)
            {
                Console.WriteLine(entry.Key + ": " + entry.Value);
            }
        }
    }
}

Output:

Output

Accessing HybridDictionary in a thread-safe manner.
one: 1
two: 2
three: 3

Explanation:

This example shows how to acquire an object (syncRoot) that can be used as a synchronisation point using hybridDict.SyncRoot . After that, the lock statement is used with this synchronization object to ensure that only one thread can access or modify the HybridDictionary at a time.

8. Item [Indexer]

The Item property of the HybridDictionary in C# is used to access or modify the value associated with a particular key in the Dictionary, which is also called the indexer. Using square bracket notation , it provides a convenient way to get or set the value associated with a key.

Syntax:

It has the following synyax:

Example

// Getting the value for a key
object value = hybridDictionary["key"];
// Setting the value for a key
hybridDictionary["newKey"] = newValue;

Example:

Let us take an example to illustrate the Item property of HybridDictionary in C#.

Example

using System;
using System.Collections; 
using System.Collections.Specialized; 
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dict.Add("one", 1);
        hybrid_Dict.Add("two", 2);
        hybrid_Dict.Add("three", 3);
        // Using the Item property (indexer) to get the value
        int valueForTwo = (int)hybrid_Dict["two"];
        Console.WriteLine("Value for key 'two': " + valueForTwo);
        // Using the Item property (indexer) to set a new value
        hybrid_Dict["four"] = 4;
        // Iterating through the Dictionary to show the updated content
        Console.WriteLine("Updated HybridDictionary:");
        foreach (DictionaryEntry entry in hybrid_Dict)
        {
            Console.WriteLine(entry.Key + ": " + entry.Value);
        }
    }
}

Output:

Output

Value for key 'two': 2
Updated HybridDictionary:
one: 1
two: 2
three: 3
four: 4

Explanation:

In this example, the Item property is used to obtain the value associated with the key "two" and set a new value for the key "four" in the HybridDictionary. After that, the program iterates through the Dictionary to display the updated content.

Constructors in HybridDictionary Class

There are four types of constructors in the HybridDictionary Class.

  • HybridDictionary Constructor
  • HybridDictionary(Boolean) constructor
  • HybridDictionary(Int32) Constructor
  • HybridDictionary(Int32, Boolean) Constructor
  • 1. HybridDictionary Constructor

The HybridDictionary class aims to offer a balance between the hash table and list performance characteristics, making it suitable for scenarios where the collection size may vary over time.

Syntax:

It has the following syntax:

Example

public HybridDictionary ();

Example:

Let us take an example to illustrate the HybridDictionary constructor in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating an instance of HybridDictionary using the default constructor
        HybridDictionary hybrid_Dictionary = new HybridDictionary();
        // Adding key-value pairs
        hybrid_Dictionary.Add("key1", "value1");
        hybrid_Dictionary.Add("key2", "value2");
        // Accessing values
        string valueForKey2 = (string)hybrid_Dictionary["key2"];
        // Displaying values
        Console.WriteLine("Key-Value pairs in HybridDictionary:");
        foreach (DictionaryEntry entry in hybrid_Dictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
    }
}

Output:

Output

Key-Value pairs in HybridDictionary:
Key: key1, Value: value1
Key: key2, Value: value2

Explanation:

a. Using Directives

The code begins by using directives to import the required namespaces. System, System.Collections , and System.Collections.Specialized are included in this code.

b. Class Declaration

The Demo class is declared.

c. Main Method

The Main method is the entry point of the program.

d. HybridDictionary Initialization

The default constructor of HybridDictionary is used to produce an instance called hybridDictionary: HybridDictionary hybridDictionary = new HybridDictionary;.

e. Adding Key-Value Pairs

Using the Add method, two key-value pairs are added to the hybrid_Dictionary.

f. Accessing Values

The value associated with the key "key2" can be retrieved using the indexer notation: string valueForKey2 = (string)hybrid_Dictionary["key2"];.

g. Displaying Values

The program iterates over the hybrid_Dictionary using a foreach loop while printing a message to the console. It prints the key and value to the console for every entry.

2. HybridDictionary(Boolean) constructor

A dictionary implementation that adapts its internal data structure dependent on the collection size is offered by the HybridDictionary class, which is typically found in the "System.Collections.Specialized" namespace. The HybridDictionary(Boolean) constructor is introduced in this hypothetical scenario, allowing developers to customise the Dictionary's behaviour.

Syntax:

It has the following syntax:

Example

public HybridDictionary (bool caseInsensitive);

Parameters

Boolean: A boolean parameter designating the preferred internal implementation method. The Dictionary may choose a list-based approach when set to false and prioritise a hash table-based approach when set to true.

Example:

Let us take an example to illustrate the HybridDictionary(Boolean) constructor in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Hypothetical HybridDictionary(Boolean) constructor
        HybridDictionary hybrid_Dictionary = new HybridDictionary(true);
        // Adding key-value pairs
        hybrid_Dictionary.Add("key1", "value1");
        hybrid_Dictionary.Add("key2", "value2");
        // Accessing values
        string valueForKey2 = (string)hybrid_Dictionary["key2"];
        // Displaying values
        foreach (DictionaryEntry entry in hybrid_Dictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
    }
}

Output:

Output

Key: key1, Value: value1
Key: key2, Value: value2

Explanation:

  • A HybridDictionary instance is created with the boolean parameter set to false. HybridDictionary hybrid_Dictionary = new HybridDictionary(false); It may indicate that the Dictionary prefers a list-based method for smaller collections.
  • Using the Add method, key-value pairs are added to the hybrid_Dictionary .
  • The value associated with the key "key2" is retrieved using the indexer notation: string valueForKey2 = (string)hybrid_Dictionary["key2"];
  • After that, the code uses a foreach loop iterates through the Dictionary, displaying each key-value pair.
  • 3. HybridDictionary(Int32) Constructor

The dictionary implementation offered by the HybridDictionary class, typically found in the "System.Collections.Specialized" namespace, which adapts its internal data structure according to the collection size. The HybridDictionary(Int32) constructor is introduced in this hypothetical scenario, allowing developers to set an initial capacity for the Dictionary.

Syntax:

It has the following syntax:

Example

public HybridDictionary (int initialSize);

Parameters

Int32: An integer parameter indicating the HybridDictionary's desired starting capacity.

Example:

Let us take an example to illustrate the HybridDictionary(Int32) constructor in C#.

Example

using System; 
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating an instance of HybridDictionary with an initial capacity
        HybridDictionary hybrid_Dictionary = new HybridDictionary(10);
        // Adding key-value pairs
        hybrid_Dictionary.Add("key1", "value1");
        hybrid_Dictionary.Add("key2", "value2");
        // Accessing values
        string valueForKey2 = (string)hybrid_Dictionary["key2"];
        // Displaying values
        foreach (DictionaryEntry entry in hybrid_Dictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
    }
}

Output:

Output

Key: key1, Value: value1
Key: key2, Value: value2

Explanation:

In this hypothetical example, the HybridDictionary(Int32) constructor is used to create an instance of the HybridDictionary with an initial capacity of 10. When the developer know s the Dictionary's expected size, it might be advantageous as it might reduce the number of reallocations and potentially improve performance.

4. HybridDictionary(Int32, Boolean) Constructor

In a hypothetical scenario where a HybridDictionary(Int32, Boolean) constructor is introduced, it might be designed to allow developers to specify both an initial capacity and a boolean parameter that influences the internal behaviour of the HybridDictionary.

Syntax:

It has the following syntax:

Example

public HybridDictionary (int initialSize, bool caseInsensitive);

Parameters

Int32: An integer parameter indicating the HybridDictionary's desired initial capacity. The number of key-value pairs that the Dictionary may initially hold without requiring reallocation is indicated by this value.

Boolean: A boolean parameter that affects the internal implementation plan. The Dictionary can choose a list-based method when set to false; otherwise, it may prioritise a hash table-based approach when set to true.

Example:

Let us take an example to illustrate the HybridDictionary(Int32, Boolean) constructor in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating an instance of HybridDictionary with initial capacity and a boolean parameter
        HybridDictionary hybrid_Dictionary = new HybridDictionary(10, true);
        // Adding key-value pairs
        hybrid_Dictionary.Add("key1", "value1");
        hybrid_Dictionary.Add("key2", "value2");
        // Accessing values
        string valueForKey2 = (string)hybrid_Dictionary["key2"];
        // Displaying values
        foreach (DictionaryEntry entry in hybrid_Dictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
    }
}

Output:

Output

Key: key1, Value: value1
Key: key2, Value: value2

Explanation:

In this example, the HybridDictionary(10, true) constructor is used to create an instance of the HybridDictionary with an initial capacity of 10 and a boolean parameter set to true.

The boolean parameter might be associated with an internal size threshold. For example, the list-based approach may be used if the number of key-value pairs in the Dictionary is below a specific threshold. If not, the hash table-based approach can be used.

Methods of HybridDictionary Class

There are several method of the HybridDictionary Class in C#. Some main methods of the HybridDictionary Class are as follows:

1. Add

The add function of the HybridDictionary Class is used to add an element to the Dictionary with a given key and value.

Syntax:

It has the following syntax:

Example

void Add(object key, object value);

Parameters

key: It is the key of the element to add to the Dictionary.

value: It is the value of the element to add to the Dictionary.

Return Type

void: No value is returned by the Add function.

Example:

Let us take an example to illustrate the add function in the HybridDictionary class in C#.

Example

using System; 
using System.Collections; 
using System.Collections.Specialized; 
class C# Tutorial 
{ 
    public static void Main() 
    { // Creating a HybridDictionary named myDict 
        HybridDictionary hybrid_Dict = new HybridDictionary(); 
        // Adding key/value pairs in myDict 
        hybrid_Dict.Add(1, "Apple"); 
        hybrid_Dict.Add(2, "Banana"); 
        hybrid_Dict.Add(3, "Orange"); 
        hybrid_Dict.Add(4, "Guava"); 
        // To get a count of key/value pairs in myDict 
        Console.WriteLine("The total key/value pairs in myDict are: " 
                                                  + hybrid_Dict.Count); 
        // Displaying the key/value pairs in myDict 
        Console.WriteLine("The key/value pairs in myDict are: "); 
        foreach(DictionaryEntry i in hybrid_Dict) 
        { 
            Console.WriteLine(i.Key + " --> " + i.Value); 
        } 
    } 
}

Output:

Output

The total key/value pairs in myDict are: 4
The key/value pairs in myDict are: 
1 --> Apple
2 --> Banana
3 --> Orange
4 --> Guava

Explanation:

The program creates a HybridDictionary , adds a few key-value pairs, prints the number of pairs in total, and then displays each key-value pair in the Dictionary.

2. Contains

The HybridDictionary class in C# has a Contains method used to determine if a given key is present in the Dictionary. It aims to determine whether an element with a given key exists in the HybridDictionary.

Syntax:

It has the following syntax:

Example

public bool Contains(object key);

Parameters

key: It is the key to locate in the HybridDictionary.

Return Type

bool: Returns true if there is an element in the HybridDictionary with the given key; otherwise, returns false.

Example:

Let us take an example to illustrate the contains function in the HybridDictionary class in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary
        HybridDictionary hybrid_Dict = new HybridDictionary();
        // Adding key/value pairs to the HybridDictionary
        hybrid_Dict.Add("Key1", "Value1");
        hybrid_Dict.Add("Key2", "Value2");
        // Checking if the HybridDictionary contains a specific key
        Console.WriteLine("Does the HybridDictionary contain Key1? " + hybrid_Dict.Contains("Key1")); 
        Console.WriteLine("Does the HybridDictionary contain Key3? " + hybrid_Dict.Contains("Key3")); 
    }
}

Output:

Output

Does the HybridDictionary contain Key1? True
Does the HybridDictionary contain Key3? False

Explanation:

Essentially, the program demonstrates how to create a HybridDictionary, add key-value pairs to it, and then use the Contains method to check if any certain keys are there. The outputs indicate whether the keys are present in the Dictionary or not.

3. Equals

The HybridDictionary class in C# has a specified Equals method on the class itself. It inherits the Equals method from the Object class, the base class for all types in C#. In order to check for reference equality, the "Object.Equals" method compares whether two object references point to the same memory address.

Syntax

It has the following syntax:

Example

public virtual bool Equals(object obj);

Parameters

obj: The Object to compare with the current Object.

Return Type

bool: It returns true if the current Object and the one supplied Object are equal; otherwise, it is false.

Example:

Let us take an example to illustrate the equals function in the HybridDictionary class in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        HybridDictionary dict_1 = new HybridDictionary();
        HybridDictionary dict_2 = new HybridDictionary();
        // Adding key-value pairs
        dict_1.Add("Key1", "Value1");
        dict_1.Add("Key2", "Value2");
        dict_2.Add("Key1", "Value1");
        dict_2.Add("Key2", "Value2");
        // Using Equals to compare references
        bool referenceEquality = object.Equals(dict_1, dict_2);
        Console.WriteLine("Reference equality: " + referenceEquality);  // Output: False (different references)
        // Checking if key-value pairs are equal
        bool contentEquality = DictionaryEquals(dict_1, dict_2);
        Console.WriteLine("Content equality: " + contentEquality);  // Output: True (same key-value pairs)
    }
    static bool DictionaryEquals(HybridDictionary dict_1, HybridDictionary dict_2)
    {
        // Check for nullity and reference equality
        if (dict_1 == dict_2)
            return true;
        // Check for nullity
        if (dict_1 == null || dict_2 == null)
            return false;
        // Check for content equality
        return dict_1.Count == dict_2.Count && Object.Equals(dict_1["Key1"], dict_2["Key1"]) && object.Equals(dict_1["Key2"], dict_2["Key2"]);
    }
}

Output:

Output

Reference equality: False
Content equality: True

Explanation:

The DictionaryEquals is a custom method in the program above that checks if two instances of HybridDictionary have the same content. Instead of comparing the references, this method compares key-value pairs.

4. GetHashCode

The HybridDictionary class in C# does not directly expose a GetHashCode method. However, it inherits the GetHashCode method from the Object class, the base class for all types in C#. The "Object.GetHashCode" method obtains a hash code for the current Object. The default implementation provided by Object is based on the Object's reference.

The default behaviour of GetHashCode is to return an integer that represents the Object's memory address.

Syntax:

It has the following syntax:

Example

public virtual int GetHashCode();

Return Type

int: It has a 32-bit signed integer hash code.

Example:

Let us take an example to illustrate the GetHashCode function in the HybridDictionary class in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        HybridDictionary dict_1 = new HybridDictionary();
        HybridDictionary dict_2 = new HybridDictionary();
        // Adding key-value pairs
        dict_1.Add("Key1", "Value1");
        dict_1.Add("Key2", "Value2");
        dict_2.Add("Key1", "Value1");
        dict_2.Add("Key2", "Value2");
        // Using GetHashCode to compare hash codes
        int hashCode_Dict1 = dict_1.GetHashCode();
        int hashCode_Dict2 = dict_2.GetHashCode();
        Console.WriteLine("HashCode of dict1: " + hashCode_Dict1);
        Console.WriteLine("HashCode of dict2: " + hashCode_Dict2);
        // Check if hash codes are equal (not guaranteed for different objects)
        Console.WriteLine("Are hash codes equal? " + (hashCode_Dict1 == hashCode_Dict2)); // Output: False
    }
}

Output:

Output

HashCode of dict1: -1710425844
HashCode of dict2: -1323148927
Are hash codes equal? False

Explanation:

By default, the GetHashCode method returns an integer that indicates the Object's memory address. Two objects with the same values but different references must usually have different hash codes.

5. Clear

The Clear method in the HybridDictionary class in C# removes all the elements from the hybrid Dictionary, effectively resetting it to an empty state.

Syntax:

It has the following syntax:

Example

public void Clear();

Parameters

void: The Clear method of the HybridDictionary class is void , which means it doesn't return any value.

Clear: When called, the hybrid Dictionary leaves empty since all key-value pairs have been removed.

Example:

Let us take an example to illustrate the Clear function in the HybridDictionary class in C#.

Example

using System;
using System.Collections; 
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary instance
        HybridDictionary hybrid_Dictionary = new HybridDictionary();
        // Adding key-value pairs to the HybridDictionary
        hybrid_Dictionary.Add(1, "Apple");
        hybrid_Dictionary.Add(2, "Banana");
        hybrid_Dictionary.Add(3, "Orange");
        // Displaying the elements before calling Clear()
        Console.WriteLine("Elements before Clear():");
        foreach (DictionaryEntry entry in hybrid_Dictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
        // Clearing the HybridDictionary
        hybrid_Dictionary.Clear();
        // Displaying the elements after calling Clear()
        Console.WriteLine("Elements after Clear():");
        foreach (DictionaryEntry entry in hybrid_Dictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
    }
}

Output:

Output

Elements before Clear():
Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Orange
Elements after Clear():

Explanation:

In this example, the HybridDictionary's elements are all eliminated using the Clear method. It is useful if we want to start with an empty collection and reset the Dictionary. Remember that when we use Clear, the Dictionary is left with zero elements.

6. CopyTo(Array, Int32)

The HybridDictionary class in C# has a CopyTo(Array, Int32) method that copies the HybridDictionary's elements into a one-dimensional array, beginning at the specified index within the array. This method is usually when transferring HybridDictionary elements to another array for further processing or manipulation.

Syntax:

It has the following syntax:

Example

public void CopyTo(Array array, int index);

Parameters

array: The one-dimensional array that is the destination of the elements copied from the HybridDictionary. Zero-based indexing is required for the array.

index: The zero-based index in the array at which copying begins.

Example:

Let us take an example to illustrate the CopyTo(Array, Int 32) function in the HybridDictionary class in C#.

Example

using System; 
using System.Collections; 
using System.Collections.Specialized; 
class C# Tutorial
{ 
	public static void Main() 
	{ 
                      // Creating a HybridDictionary named hybrid_Dict
		HybridDictionary hybrid_Dict = new HybridDictionary(); 
		// Adding key/value pairs in hybrid_Dict 
		hybrid_Dict.Add(1, "Apple"); 
		hybrid_Dict.Add(2, "Banana"); 
		hybrid_Dict.Add(3, "Orange"); 
		DictionaryEntry[] my_Arr = new DictionaryEntry[hybrid_Dict.Count]; 
		hybrid_Dict.CopyTo(my_Arr, 0); 
		for (int i = 0; i < my_Arr.Length; i++) 
	           Console.WriteLine(my_Arr[i].Key + " --> "+ my_Arr[i].Value); 
	} 
}

Output:

Output

1 --> Apple
2 --> Banana
3 --> Orange

Explanation:

The code adds key-value pairs, copies its elements to a DictionaryEntry array , and then displays the key-value pairs from the array to demonstrate how to use a HybridDictionary.

7. GetEnumerator

An enumerator that iterates throughout the key-value pairs in the HybridDictionary may be obtained by calling the GetEnumerator method in the C# HybridDictionary class. An IDictionaryEnumerator interface is returned by this method, allowing it to traverse the elements of the Dictionary in a forward-only, read-only manner.

Syntax

Example

public IDictionaryEnumerator GetEnumerator();

Return Type

IDictionaryEnumerator: It represents an enumerator for a collection of key-value pairs.

Example:

Let us take an example to illustrate the GetEnumerator function in the HybridDictionary class in C#.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary instance
        HybridDictionary hybrid_Dictionary = new HybridDictionary();
        // Adding key-value pairs to the HybridDictionary
        hybrid_Dictionary.Add(1, "Apple");
        hybrid_Dictionary.Add(2, "Banana");
        hybrid_Dictionary.Add(3, "Orange");
        // Obtaining an enumerator using GetEnumerator()
        IDictionaryEnumerator enumerator = hybrid_Dictionary.GetEnumerator();
        // Iterating through the key-value pairs using the enumerator
        Console.WriteLine("Key-Value pairs in the HybridDictionary:");
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Key: {enumerator.Key}, Value: {enumerator.Value}");
        }
    }
}

Output:

Output

Key-Value pairs in the HybridDictionary:
Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Orange

Explanation:

The code shows how to create a HybridDictionary, add key-value pairs, use GetEnumerator to obtain an enumerator, iterate through the key-value pairs using the enumerator, and display the output on the console. It is a simple example of how to access and handle the elements of a HybridDictionary using its enumerator.

8. Remove(Object)

Use the remove(Object) method DictionaryridDictionary class in C# to remove an element from the Dictionary with a certain key. The method is ineffective if the Dictionary cannot find the key.

Syntax:

It has the following syntax:

Example

public void Remove(object key);

Parameters

key: It is the key of the element that is used to remove from the HybridDictionary.

Example:

Let us take an example to illustrate the remove function in the HybridDictionary class in C#.

Example

using System;
using System.Collections; 
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Creating a HybridDictionary instance
        HybridDictionary hybrid_Dictionary = new HybridDictionary();
        // Adding key-value pairs to the HybridDictionary
        hybrid_Dictionary.Add(1, "Mango");
        hybrid_Dictionary.Add(2, "Banana");
        hybrid_Dictionary.Add(3, "Orange");
        // Displaying the elements before removal
        Console.WriteLine("Elements before removal:");
        foreach (DictionaryEntry entry in hybrid_Dictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
        // Removing an element by key
        hybrid_Dictionary.Remove(2);
        // Displaying the elements after removal
        Console.WriteLine("Elements after removal:");
        foreach (DictionaryEntry entry in hybrid_Dictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
    }
}

Output:

Output

Elements before removal:
Key: 1, Value: Mango
Key: 2, Value: Banana
Key: 3, Value: Orange
Elements after removal:
Key: 1, Value: Mango
Key: 3, Value: Orange

Explanation:

The code demonstrates how to create a HybridDictionary, add key-value pairs, remove an item with a certain key, and then display the elements before and after the removal. The output will demonstrate the effective removal of the key-value pair associated with key 2 from the Dictionary.

9. GetType

The GetType method is derived from the "System.Object" class, which is the base class for all C# types and is not specific to the HybridDictionary class in C#. Therefore, the GetType method is accessible to all classes in C#. An instance of the "System.Type" class , which represents the runtime type information of the current Object, is returned by the GetType function. This data contains specifics like the class name, the assembly in which it is declared, the methods it exposes, and other metadata.

Syntax:

It has the following syntax:

Example

public Type GetType ();

Parameters

public: The method can be accessed from outside the class, as indicated by the public keyword. This instance of the "System.Object" class has a public method named GetType that may be called on any instance of an object.

Type: Runtime type information is represented by the Type class in the System namespace. An instance of this Type class is returned by the GetType method.

GetType: It is the name of the method. It's a standard method provided by the base class "System.Object" inherited by all classes in C#.

Example:

Let us take an example to illustrate the GetType function in the HybridDictionary class in C#.

Example

using System;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Create an instance of HybridDictionary
        HybridDictionary hybrid_Dictionary = new HybridDictionary();
        // Use GetType() to get the runtime type information
        Type type = hybrid_Dictionary.GetType();
        // Display some information about the type
        Console.WriteLine("Type Name: " + type.FullName);
        Console.WriteLine("Assembly: " + type.Assembly.FullName);
        // Other information about the type can be accessed through the Type class
        Console.WriteLine("Is Class: " + type.IsClass);
        Console.WriteLine("Is Interface: " + type.IsInterface);
        // You can also check if an object is of a specific type using GetType()
        if (hybrid_Dictionary is HybridDictionary)
        {
            Console.WriteLine("The object is of type HybridDictionary");
        }
    }
}

Output:

Output

Type Name: System.Collections.Specialized.HybridDictionary
Assembly: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Is Class: True
Is Interface: False
The Object is of type HybridDictionary

Explanation:

In this example, an instance of HybridDictionary is called with GetType, and different details about the type are obtained using the Type object returned.

10. ToString

The ToString method is not specific to the HybridDictionary class in C#. Instead, it is inherited from the "System.Object" class, the base class for all types in C#. Therefore, any class in C# can access the ToString method.

In order to obtain a string representation of an object, use the ToString method. In derived classes, it is usually overridden to provide a more meaningful string representation depending on the specific characteristics of the class.

Syntax:

It has the following syntax:

Example

public override string ToString();

Example:

Let us take an example to illustrate the ToString function in the HybridDictionary class in C#.

Example

using System;
using System.Collections.Specialized;
class C# Tutorial
{
    static void Main()
    {
        // Create an instance of HybridDictionary
        HybridDictionary hybrid_Dictionary = new HybridDictionary();
        hybrid_Dictionary.Add("Key1", "Value1");
        hybrid_Dictionary.Add("Key2", "Value2");
        // Use ToString() to get a string representation of the HybridDictionary
        string hybrid_DictionaryString = hybrid_Dictionary.ToString();
        // Display the string representation
        Console.WriteLine("HybridDictionary as a string: " + hybrid_DictionaryString);
    }
}

Output:

Output

HybridDictionary as a string: System.Collections.Specialized.HybridDictionary

Explanation:

When the HybridDictionary object is concatenated with a string in the "Console.WriteLine" statement, the ToString method is implicitly executed. If necessary, we can explicitly call ToString. Classes frequently override the ToString method for a custom string representation. The default implementation in Object returns the fully qualified name of the type.

Input Required

This code uses input(). Please provide values below: