Incrementing a numerical value in a dictionary

Your code is fine. But here's a way to simplify in a way that doesn't require branching in your code:

int currentCount;

// currentCount will be zero if the key id doesn't exist..
someDictionary.TryGetValue(id, out currentCount); 

someDictionary[id] = currentCount + 1;

This relies on the fact that the TryGetValue method sets value to the default value of its type if the key doesn't exist. In your case, the default value of int is 0, which is exactly what you want.


UPD. Starting from C# 7.0 this snippet can be shortened using out variables:

// declare variable right where it's passed
someDictionary.TryGetValue(id, out var currentCount); 
someDictionary[id] = currentCount + 1;

As it turns out it made sense to use the ConcurrentDictionary which has the handy upsert method: AddOrUpdate.

So, I just used:

someDictionary.AddOrUpdate(id, 1, (id, count) => count + 1);