How to update the value stored in a Dictionary in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. In Dictionary, the key cannot be null, but value can be. A key must be unique. Duplicate keys are not allowed if we try to use duplicate key then compiler will throw an exception.

As mentioned above a value in a dictionary can be updated by using its key as the key is unique for every value.

Syntax

Following is the syntax for updating a dictionary value −

myDictionary[myKey] = myNewValue;

You can also use the TryGetValue method for safe updates −

if (myDictionary.TryGetValue(myKey, out var currentValue)) {
    myDictionary[myKey] = myNewValue;
}

Using Direct Key Assignment

The simplest way to update a dictionary value is using the indexer syntax. Let's take a dictionary of students having id and name. Now if we want to change the name of the student having id 2 from "Mrk" to "Mark" −

using System;
using System.Collections.Generic;

namespace DemoApplication {
    class Program {
        static void Main(string[] args) {
            Dictionary<int, string> students = new Dictionary<int, string> {
                { 1, "John" },
                { 2, "Mrk" },
                { 3, "Bill" }
            };
            
            Console.WriteLine($"Name of student having id 2: {students[2]}");
            students[2] = "Mark";
            Console.WriteLine($"Updated Name of student having id 2: {students[2]}");
        }
    }
}

The output of the above code is −

Name of student having id 2: Mrk
Updated Name of student having id 2: Mark

Using TryGetValue for Safe Updates

To avoid KeyNotFoundException when the key might not exist, use TryGetValue to check before updating −

using System;
using System.Collections.Generic;

namespace DemoApplication {
    class Program {
        static void Main(string[] args) {
            Dictionary<int, string> students = new Dictionary<int, string> {
                { 1, "John" },
                { 2, "Alice" },
                { 3, "Bill" }
            };
            
            // Safe update - check if key exists first
            int studentId = 2;
            if (students.TryGetValue(studentId, out string currentName)) {
                Console.WriteLine($"Current name: {currentName}");
                students[studentId] = "Alice Johnson";
                Console.WriteLine($"Updated name: {students[studentId]}");
            }
            
            // Try updating non-existing key
            int nonExistentId = 5;
            if (students.TryGetValue(nonExistentId, out string name)) {
                students[nonExistentId] = "New Name";
            } else {
                Console.WriteLine($"Student with id {nonExistentId} does not exist");
            }
        }
    }
}

The output of the above code is −

Current name: Alice
Updated name: Alice Johnson
Student with id 5 does not exist

Using ContainsKey Method

Another approach is to use the ContainsKey method to verify key existence before updating −

using System;
using System.Collections.Generic;

namespace DemoApplication {
    class Program {
        static void Main(string[] args) {
            Dictionary<string, int> scores = new Dictionary<string, int> {
                { "Math", 85 },
                { "English", 92 },
                { "Science", 78 }
            };
            
            string subject = "Math";
            if (scores.ContainsKey(subject)) {
                Console.WriteLine($"Old {subject} score: {scores[subject]}");
                scores[subject] = 95;
                Console.WriteLine($"New {subject} score: {scores[subject]}");
            }
            
            // Adding or updating with indexer
            scores["History"] = 88; // Adds new key-value pair
            Console.WriteLine($"History score: {scores["History"]}");
        }
    }
}

The output of the above code is −

Old Math score: 85
New Math score: 95
History score: 88

Comparison of Update Methods

Method Behavior if Key Exists Behavior if Key Doesn't Exist
dict[key] = value Updates existing value Adds new key-value pair
TryGetValue + Update Safe update after verification No action, returns false
ContainsKey + Update Updates after key check No action, returns false

Conclusion

Dictionary values in C# can be updated using the indexer syntax dict[key] = newValue. For safer operations, use TryGetValue or ContainsKey to check key existence before updating. The indexer approach automatically adds new entries if the key doesn't exist.

Updated on: 2026-03-17T07:04:36+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements