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

CsharpServer Side ProgrammingProgramming

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.

myDictionary[myKey] = myNewValue;


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".

 Live Demo

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
Updated on 04-Aug-2020 07:29:38