locked
How to update dictionary value in C#; RRS feed

  • Question

  • I have

    Dictionary<int, myClass> ActiveTabIndex = new Dictionary<int, myClass>();
    public class myClass
        {
            public int TabIndex { get; set; }
            public string OdSessionId { get; set; }
            public string TextBoxValue { get; set; }
        }

    i am adding value to dictionary like 

    ActiveTabIndex.Add(1, new myClass{ TabIndex = 1, OdSessionId = "S", TextBoxValue=""});

    now i want to update TextBoxValue for Key 1, 
    like

    ActiveTabIndex[1] = new myClass{ TextBoxValue="something"};
    but its Resting the other value to default, 
    How Can I update The value of dictionary for the specific key with out overriding Other value.



    Tuesday, July 31, 2018 12:08 PM

All replies

  • Create it as static. But it should be wrong to expose dictionary as public to work with it. Use encapsulation princip to Add and Get values to/from dictionary. It means you will implement public static void Add(myClass myClassObject) method and public static myClass GetmyClassObjectByKey(int key) method to work with dictionary.
    Tuesday, July 31, 2018 12:31 PM
  • Try should work:

    ActiveTabIndex[1].TextBoxValue = "something";

    Tuesday, July 31, 2018 12:38 PM
  • Because you are creating a new object with new state but you need to just update the state of current object.

    You need to do it this way :

    ActiveTabIndex[1].TextBoxValue="something";


    Now you will have just TextBoxValue property of the instance updated with the other properties value retained.

    Hope it helps.


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites


    Tuesday, July 31, 2018 12:41 PM
  • Because I am creating a new object with new state but you need to just update the state of current object.

    I need to do it this way

    ActiveTabIndex[1].TextBoxValue = "Something"


    Tuesday, July 31, 2018 12:50 PM