Javatpoint Logo
Javatpoint Logo

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.

2. Pairs of Key-Value

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

3. 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.

4. Efficient for Small Collections

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

5. 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.

2. Balancing Memory and Performance

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

3. 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:

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

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 number_Of_Elements 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:

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

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#.

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:

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

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:

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

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:

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

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:

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

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:

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

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.

  1. HybridDictionary() Constructor
  2. HybridDictionary(Boolean) constructor
  3. HybridDictionary(Int32) Constructor
  4. 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:

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

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 hybrid_Dictionary: HybridDictionary hybrid_Dictionary = 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:

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#.

Output:

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

Explanation:

  1. 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.
  2. Using the Add method, key-value pairs are added to the hybrid_Dictionary.
  3. The value associated with the key "key2" is retrieved using the indexer notation: string valueForKey2 = (string)hybrid_Dictionary["key2"];
  4. 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:

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#.

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 knows 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:

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#.

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:

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#.

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:

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#.

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:

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#.

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:

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#.

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:

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#.

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:

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#.

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

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#.

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:

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#.

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:

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#.

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:

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

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.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA