VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/csharp-sorteddictionary-add-method/

⇱ C# | SortedDictionary.Add() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C# | SortedDictionary.Add() Method

Last Updated : 11 Jul, 2025
This is used to add a specified key and value to the sorted dictionary. The elements are sorted according to TKey. Syntax:
public void Add (TKey key, TValue value);
Parameters:
key: It is the key of the element to add. value: It is the value of the element to add. The value can be null for reference types.
Exceptions:
  • ArgumentNullException : If the key is null.
  • ArgumentException : If an element with the same key already exists in the Dictionary.
Below are the programs to illustrate the use of Dictionary<TKey, TValue>.Add() Method: Example 1:
Output:
Total key/value pairs in myDict are : 6
The key/value pairs in myDict are : 
Key = Australia, Value = Canberra
Key = Belgium, Value = Brussels
Key = China, Value = Beijing
Key = India, Value = New Delhi
Key = Netherlands, Value = Amsterdam
Key = Russia, Value = Moscow
Example 2:
Output:
An element with Key = "Russia" already exists.
Note:
  • A key cannot be null, but a value can be. If the value type TValue is a reference type.
  • This method is an O(log n) operation, where n is Count of elements in the SortedDictionary.
Reference:
Comment

Explore