This post will discuss how to increment a numeric value in a Dictionary<TKey,TValue> in C#.

1. Using IDictionary<TKey,TValue>.TryGetValue() Method

The IDictionary<TKey,TValue>.TryGetValue() method retrieves the value associated with the specified key if the key is found; otherwise, it sets the value to the default value of the corresponding type of the value parameter. The following code creates an extension method to increment the numeric value of the specified key using the TryGetValue() method.

Download  Run Code

Output:

[A, 2], [B, 2], [C, 3]

 
Beginning from C# 7.0, this can be further shortened using out parameter modifier. It allows us to declare the out variable in the argument list of the method call and prevents a separate variable declaration.

Download  Run Code

Output:

[A, 2], [B, 2], [C, 3]

2. Using Dictionary<TKey,TValue>.ContainsKey() Method

As evident from the above example, TryGetValue() method effectively combines the functionality of the ContainsKey() method and indexer property. The following code example uses the Item[] property increments the existing value of a key if it exists, otherwise, insert it into the dictionary.

Download  Run Code

Output:

[A, 2], [B, 2], [C, 3]

That’s all about incrementing a numeric value in a Dictionary in C#.