0

I have a dictionary of

IDictionary<TKey, long> dictionary;

Instead of using https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.getvalueordefault?view=net-6.0 to add values to the list like so:

dictionary[key] = dictionary.GetValueOrDefault(key) + value;

I would like to just do:

dictionary[key] += value;

Is there a way to override or subclass or wrap dictionary to do this correctly?

user2460953
  • 319
  • 1
  • 3
  • 10
  • What exactly *are* you trying to do? Do you want to accumulate the value, or do you want to add the value to the dictionary only if it's not there? If you do `dictionary[key] += value;` a second time, do you want it to replace the value or add to what's already there? – madreflection Dec 14 '21 at 18:52
  • @madreflection Add to the value if it is there. If it is not there, set the value (or add it to the default value, which is 0). – user2460953 Dec 14 '21 at 18:54
  • And if it already exists, what should it do? – madreflection Dec 14 '21 at 18:55
  • Add to the current value that is there. Same as this does: dictionary.GetValueOrDefault(key) + value; – user2460953 Dec 14 '21 at 18:56
  • Yes, works fine: Dictionary count = new Dictionary(); count["a"] = count.GetValueOrDefault("a") + 1; Console.WriteLine(count["a"]); Prints 1 – user2460953 Dec 14 '21 at 19:02
  • 1
    You can't overload operators for types you don't control, so you're not going to get `+=` to do what you want. Write an extension method and give it a meaningful name. And even if you had control over the type, you can't overload `+=`. You would have to redefine the indexer to return the default value if the item doesn't exist. – madreflection Dec 14 '21 at 19:03

0 Answers0