-1

I'd like to histories Person Data modeled in a Class:

public class PersonModel : ViewModelBase
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    ...

}

The Person data is modified during runtime and periodically historised:

public MainViewModel() {
    List<PersonModel> histItem = new List<PersonModel>();
    PersonModel item = new PersonModel();
    item.FirstName = "Vorname 1";
    histItem.Add(item);
    item.FirstName = "Vorname 2";
    histItem.Add(item);
}

When I change item (like in secound last line) histItem is also changed

histItem[0].FirstName = "Vorname 2";

When I Add item the second time to histItem I have got two duplicated List entities. Collection has got the same behavior.

I want store 'item' as a persistent, later not changeable snapshot.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
rema11
  • 1
  • 1
    You have to actually make a snapshot of its current state. You're adding *references* to the same object twice, and modifying the object as well, which will overwrite the previous changes. This does not work as you've already noticed. So you need a snapshot mechanism. – Lasse V. Karlsen Oct 12 '15 at 12:48
  • You have to create a new item each time: `item = new PersonModel();` – D Stanley Oct 12 '15 at 12:49

1 Answers1

0

Use like this :

 List<PersonModel> histItem = new List<PersonModel>();
 PersonModel item = new PersonModel();
 item.FirstName = "Vorname 1";
 histItem.Add(item);
 item = new PersonModel();
 item.FirstName = "Vorname 2";
 histItem.Add(item);

or

 histItem.Add(new PersonModel(){FirstName="value 1"});
 histItem.Add(new PersonModel() { FirstName = "value 2" });
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • A problem with this approach is that in general only a small amount of data will probably change, such that it probably not advisable to create\ a new instance each time. – Willem Van Onsem Oct 12 '15 at 12:53
  • Thanks a lot for this quick answer. I'm sorry, I didn't recognise that this question has already been asked. There is a bigger problem while creating a new instance all times: The Data is getting lost. The ‘PersonModel’ class is huge (containing approximately 100 members and multiple other generic lists), only a small amount is printed out above. Every time a new instance is created the new instance (item) needs to be filled member-wise with the data. The ‘PersonModel’ class is subject to be changed. Is there no other solution for this problem? Any other ideas? – rema11 Oct 13 '15 at 09:29
  • Sorry what do you mean with 'inbox me'? – rema11 Oct 13 '15 at 12:13
  • send details to my mail, `text2meanytime@gmail.com` – sujith karivelil Oct 13 '15 at 12:14