This property is used to get or set the value associated with the specified key in the Dictionary.
Syntax:
public TValue this[TKey key] { get; set; }
Here,
key is the Key of the value to get or set.
Property Value: It is the value associated with the specified key. If the specified key is not found, a get operation throws a
KeyNotFoundException, and a set operation creates a new element with the specified key.
Exceptions:
- ArgumentNullException: If the key is null.
- KeyNotFoundException: If the property is retrieved and key does not exist in the collection.
Example:
Output:
Key = Australia, Value = Canberra
Key = Belgium, Value = Brussels
Key = Netherlands, Value = Amsterdam
Key = China, Value = Beijing
Key = Russia, Value = Moscow
Key = India, Value = New Delhi
Value associated with Russia: Moscow
Value associated with Russia After Setting: Saint Petersburg
Value associated with India: New Delhi
Value associated with India After Setting: Mumbai
Key = Australia, Value = Canberra
Key = Belgium, Value = Brussels
Key = Netherlands, Value = Amsterdam
Key = China, Value = Beijing
Key = Russia, Value = Saint Petersburg
Key = India, Value = Mumbai
Reference: