I'm using a Dictionary<int, KeyValuePair<bool, int>>
to hold data.
From time to time I need to increment the int
in the KeyValuePair
, but it won't let me, because it has no setter. Is there a way to increment it?
Code sample:
Dictionary<int, KeyValuePair<bool, int>> mDictionary =
new Dictionary<int, KeyValuePair<bool, int>>();
mDictionary[trapType].Value++;
//Error: The property KeyValuePair<TKey, Tvalue>>.Value has no setter
Is there a way to increment it?
No. KeyValuePair
is immutable - it's also a value type, so changing the value of the Value
property after creating a copy wouldn't help anyway.
You'd have to write something like this:
var existingValue = mDictionary[trapType];
var newValue = new KeyValuePair<bool, int>(existingValue.Key,
existingValue.Value + 1);
mDictionary[trapType] = newValue;
It's pretty ugly though - do you really need the value to be a KeyValuePair
?