C# C# Console Application

How to add an item to a Dictionary in C#1 min read

.Net framework Dictionary<TKey, TValue>.Add() method allow us to add the specified key and value to the dictionary. dictionary Add() method exists in System.Collections.Generic namespace. Add() method need to pass two parameters named ‘key’ and ‘value’.

the ‘key’ parameter value type is ‘TKey’ which represents the key of the element to add. ‘value’ parameter value type is ‘TValue’ which represents the value of the element to add into dictionary. this value can be null for reference types. ‘key’ cannot be null. this method implements as IDictionary<TKey, TValue>.Add(TKey, TValue).

dictionary Add() method throw ArgumentNullException exception if the ‘key’ parameter value is null. this method throw ArgumentException exception, if an element with the same key already exists in Dictionary<TKey, TValue>.

the following c# example code demonstrate us how can we add a key and value pair to dictionary programmatically in an application.

C# Code:




Leave a Comment