KeyValuePair<TKey, TValue> is immutable. You need to create a new one with the modifified key or value. What you actually do next depends on your scenario, and what exactly you want to do...
public class KeyVal<Key, Val>
{
public Key Id { get; set; }
public Val Text { get; set; }
public KeyVal() { }
public KeyVal(Key key, Val val)
{
this.Id = key;
this.Text = val;
}
}
so we can make it use in wherever in KeyValuePair.
The KeyValuePair<TKey, TValue> is a struct and struct in C# is value type and mentioned to be immutable. The reason is obvious, the Dictionary<TKey,TValue> should be a high-performance data structure. Using a reference type instead of value type would use too much memory overhead. Unlike a directly stored value type in a dictionary, in addition the 32bit or 64bit references for each entry in the dictionary would be allocated. These references would be pointed to heap for entry instance. Overall performance would be decreased rapidly.
The Microsoft rules for choosing struct over class which Dictionary<TKey,TValue> satisfies:
✔️ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
❌ AVOID defining a struct unless the type has all of the following characteristics:
It logically represents a single value, similar to primitive types (int, double, etc.).