IDictionary Interface

Represents a collection of key/value pairs.

Namespace: System.Collections

Assembly: System.Private.CoreLib

The IDictionary interface represents a collection that contains key/value pairs. Keys must be unique within the dictionary.

Members

Properties

Name Type Description
Count int Gets the number of elements contained in the ICollection.
IsFixedSize bool Gets a value indicating whether the IDictionary has a fixed size.
IsReadOnly bool Gets a value indicating whether the IDictionary is read-only.
Keys ICollection Gets an ICollection containing the keys of the IDictionary.
Values ICollection Gets an ICollection containing the values of the IDictionary.
this[object key] object Gets or sets the element with the specified key.

Methods

Name Description
Add(object key, object value) Adds an element with the specified key and value to the IDictionary.
Clear() Removes all elements from the IDictionary.
Contains(object key) Determines whether the IDictionary contains an element with the specified key.
GetEnumerator() Returns an IDictionaryEnumerator that iterates through the IDictionary.
Remove(object key) Removes the element with the specified key from the IDictionary.

Remarks

The IDictionary interface is the non-generic equivalent of the System.Collections.Generic.IDictionary<TKey, TValue> interface. It provides basic functionality for collections that map keys to values.

When implementing IDictionary, consider the following:

Example

This example demonstrates using a concrete implementation of IDictionary, such as Hashtable.
// Using a Hashtable, which implements IDictionary System.Collections.IDictionary myDictionary = new System.Collections.Hashtable(); // Add elements myDictionary.Add("Fruit", "Apple"); myDictionary.Add("Color", "Red"); myDictionary.Add("Number", 7); // Access elements Console.WriteLine($"The value for 'Fruit' is: {myDictionary["Fruit"]}"); // Check if a key exists if (myDictionary.Contains("Color")) { Console.WriteLine("The dictionary contains the key 'Color'."); } // Iterate through the dictionary Console.WriteLine("\nDictionary contents:"); foreach (System.Collections.DictionaryEntry entry in myDictionary) { Console.WriteLine($"{entry.Key}: {entry.Value}"); } // Remove an element myDictionary.Remove("Number"); Console.WriteLine("\nAfter removing 'Number':"); Console.WriteLine($"Count: {myDictionary.Count}");

Related Interfaces