0

I have a Message object and I already add this object to list but when I update Message object, the list Item of Message object that is already add is update too. how to make list not update even the Message object is changed?

    MessageModel Message = new MessageModel();
    Message.Name = "MyName";
    BindingList<MessageModel> list = new BindingList<MessageModel>();
    list.Add(Message); // list[0].Name = MyName
    Message.Name = "New Name"; //list[0].Name= New Name
Safi Na
  • 15
  • 7

1 Answers1

1

MessageModel is a class - a reference type. When you add it to the list you are adding a reference to the object which is the same as the reference stored in the Message variable.

There is effectively only one object and both the message variable and the list are pointing at it. If you want to change the name of the Message variable and not affect the list you will have to first create a new object and assign it to Message:

MessageModel Message = new MessageModel();
Message.Name = "MyName";
BindingList<MessageModel> list = new BindingList<MessageModel>();
list.Add(Message); // list[0].Name = MyName
Message = new MessageModel();
Message.Name = "New Name"; //list[0].Name = MyName
SBFrancies
  • 3,987
  • 2
  • 14
  • 37