KeyValuePair struct has read-only properties (Key and Value), so I made a custom class in order to replace it:
public class XPair<T, U>
{
// members
private KeyValuePair<T, U> _pair;
// constructors
public XPair()
{
_pair = new KeyValuePair<T, U>();
}
public XPair(KeyValuePair<T, U> pair)
{
_pair = pair;
}
// methods
public KeyValuePair<T, U> pair
{
get { return _pair; }
set { _pair = value; }
}
public T key
{
get { return _pair.Key; }
set { _pair = new KeyValuePair<T, U>(value, _pair.Value); }
}
public U value
{
get { return _pair.Value; }
set { _pair = new KeyValuePair<T, U>(_pair.Key, value); }
}
}
Is it possible for this class to also apply to “foreach” usage with Dictionary? Example:
Dictionary<String, Object> dictionary = fillDictionaryWithData();
foreach(XPair<String, Object> pair in dictionary) {
// do stuff here
}
That would be possible if your class would implement a conversion operator from
KeyValuePair<TKey, TValue>.But it still wouldn’t work the way you expect, because changing the key or the value of
pairinside the loop will have no effect on thedictionary. Key and value in the dictionary will remain unchanged.If you want to change the value inside a dictionary, simply use
dictionary[key] = newValue;If you want to change a key, I guess that you don’t really want a
Dictionary<TKey, TValue>. AnIEnumerable<XPair<TKey, TValue>>might be more appropriate.If you really need a Dictionary, you can use the following code to “change” a key: