Conceptually, KeyValuePair<TKey,TValue>
is just a pair of variables, Key
and Value
. Had Microsoft implemented it with exposed public fields Key
and Value
, the semantics of it would have been perfect; when used as a ForEach
control variable it would have been immutable, but one could have updated the Key or Value field of an ordinary variable or array element without having to update the other.
Unfortunately, Microsoft seems to have been unwilling to have framework types expose any public fields, even for types like KeyValuePair<TKey,TValue>
or Drawing.Rectangle
whose semantics dictate that (1) the type must be a struct; (2) its entire state is visible in a fixed set of properties (there may be other computed properties beyond those which define an object's state), and (3) those properties may be assigned any combination of values suitable for their types. Consequently, Microsoft only considered the possibilities of exposing the members comprising the types' state as read-only properties, or as read-write properties. Using read-write properties would mean that code like:
for each (var item in myDictionary)
item.Value += 1;
or
...assuming MyList is a List<Drawing.Rectangle>
MyList[3].Width += 9;
would be interpreted by the existing C# compiler as either
for each (var item in myDictionary)
{ var temp = item; temp .Value += 1; }
or
...assuming MyList is a List<Drawing.Rectangle>
{ temp = MyList[3]; temp.Width += 9; }
both of yield horrible behavior which is almost certainly not what the programmer intended. The implementers of .net decided that the value of having the members of KeyValuePair<TKey,TValue>
be individually mutable did not justify the danger posed by the former, but the usefulness of modifying individual members of Rectangle
was sufficient to justify the danger posed by second. Note that neither example would have had to pose any danger had the types used exposed fields rather than properties, since writing to a field of a temporary struct has never been permissible, even when calling property setters was.