KeyValuePair
C# programming
data structures
value modification
coding tutorial

How to modify a KeyValuePair value?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

You cannot directly modify the value inside a KeyValuePair<TKey, TValue> because KeyValuePair is immutable. If you need a different value, you either create a new KeyValuePair or update the underlying collection, such as a Dictionary, that originally produced the pair.

KeyValuePair is a value snapshot

KeyValuePair<TKey, TValue> is commonly seen when you enumerate a dictionary:

csharp
1using System;
2using System.Collections.Generic;
3
4var scores = new Dictionary<string, int>
5{
6    ["alice"] = 10,
7    ["bob"] = 20
8};
9
10foreach (KeyValuePair<string, int> pair in scores)
11{
12    Console.WriteLine($"{pair.Key}: {pair.Value}");
13}

Each pair is a snapshot-like value. Its Key and Value properties are read-only. That is why this does not compile:

csharp
pair.Value = 99;

The compiler rejects it because the struct does not expose a settable property.

Create a new pair if you only need a modified pair object

If you are not trying to update a dictionary and only want a new pair value, create one:

csharp
1using System;
2using System.Collections.Generic;
3
4var original = new KeyValuePair<string, int>("alice", 10);
5var updated = new KeyValuePair<string, int>(original.Key, 99);
6
7Console.WriteLine(updated.Value); // 99

This does not mutate original. It creates a separate KeyValuePair with the same key and a different value.

Update the dictionary when the pair came from a dictionary

In most real code, the question is not "how do I mutate the pair object?" It is "how do I change the value stored in the dictionary?" The correct answer is to update the dictionary by key:

csharp
1using System;
2using System.Collections.Generic;
3
4var scores = new Dictionary<string, int>
5{
6    ["alice"] = 10
7};
8
9scores["alice"] = 99;
10Console.WriteLine(scores["alice"]); // 99

That changes the collection, and any future enumeration will return a pair with the new value.

Be careful when iterating

Developers often try to modify values inside a foreach loop over the dictionary:

csharp
1foreach (var pair in scores)
2{
3    // pair.Value = 99;  // not allowed
4}

If you need to update multiple entries, iterate over the keys instead:

csharp
1var keys = new List<string>(scores.Keys);
2
3foreach (var key in keys)
4{
5    scores[key] = scores[key] + 1;
6}

Copying the keys first is a safe pattern when updates might otherwise interfere with enumeration.

Choose the right type for mutable data

If your design requires a mutable pair-like object, KeyValuePair may not be the right type. Possible alternatives include:

  • updating a dictionary directly
  • defining your own mutable class or struct
  • using a record or tuple when immutability is acceptable

The right choice depends on whether you need a collection entry, a temporary returned value, or a mutable domain object.

Why KeyValuePair is designed this way

Immutability makes enumeration behavior predictable. If dictionary entries exposed mutable pair objects directly during iteration, code would be much easier to misuse. By making KeyValuePair read-only, .NET pushes you toward modifying the actual collection instead of a temporary view of its contents.

Common Pitfalls

  • Trying to assign to pair.Value inside a foreach loop.
  • Assuming that changing a copied KeyValuePair will update the dictionary.
  • Replacing the pair object when the real goal was to update the underlying collection.
  • Modifying a dictionary during enumeration without taking a safe approach such as copying keys first.
  • Using KeyValuePair when the design really calls for a mutable custom type.

Summary

  • 'KeyValuePair<TKey, TValue> is immutable, so you cannot directly change its value.'
  • Create a new KeyValuePair if you only need a new pair object.
  • Update the dictionary by key when the pair came from a dictionary.
  • Do not try to mutate dictionary entries through the foreach enumeration variable.
  • If you truly need mutable pair objects, use a different type.

Course illustration
Course illustration

All Rights Reserved.