OrderedDictionary.Add(Object, Object) Method

Definition

Adds an entry with the specified key and value into the OrderedDictionary collection with the lowest available index.

C#
public void Add(object key, object value);
C#
public void Add(object key, object? value);

Parameters

key
Object

The key of the entry to add.

value
Object

The value of the entry to add. This value can be null.

Implements

Exceptions

The OrderedDictionary collection is read-only.

An element with the same key already exists in the OrderedDictionary collection.

Examples

The following code example demonstrates the creation and population of an OrderedDictionary collection. This code is part of a larger code example that can be viewed at OrderedDictionary.

C#
// Creates and initializes a OrderedDictionary.
OrderedDictionary myOrderedDictionary = new OrderedDictionary();
myOrderedDictionary.Add("testKey1", "testValue1");
myOrderedDictionary.Add("testKey2", "testValue2");
myOrderedDictionary.Add("keyToDelete", "valueToDelete");
myOrderedDictionary.Add("testKey3", "testValue3");

ICollection keyCollection = myOrderedDictionary.Keys;
ICollection valueCollection = myOrderedDictionary.Values;

// Display the contents using the key and value collections
DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);

Remarks

A key cannot be null, but a value can be.

You can also use the Item[] property to add new elements by setting the value of a key that does not exist in the OrderedDictionary collection; however, if the specified key already exists in the OrderedDictionary, setting the Item[] property overwrites the old value. In contrast, the Add method does not modify existing elements but instead throws ArgumentException.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0