2

As I added some objects of class A to my List, I realized that whenever that object changes although it is new’ed again and again, the contents of list change, probably because there is pass by reference, I know that. How can I avoid the change in the case below:

List<A> listA;

List<B> listB = SomeFuncReturnsListB();

A a = new A();

a.Attribute1 = listB;

listA.Add(new A(){Attribute1=a.Attribute1}); 
kiafiore
  • 1,071
  • 2
  • 11
  • 27
  • 1
    Maybe this is what you need: https://stackoverflow.com/questions/78536/deep-cloning-objects – Legit007 Sep 17 '21 at 07:17
  • What are you asking for? I'm struggling to understand. Are you asking how to copy a list so that you can add an item to `listA` without it affecting the contents of `listB`, or are you asking about deep cloning objects? – ProgrammingLlama Sep 17 '21 at 07:25
  • @Llama The question is about how to add objects to `listA` without changing its contents. The contents of `listA` keeps changing in the example code given. I mean that all the elements of list turns to the last added element by saying “keeps changing”. My intention was that the reason may be the `listB` in the object `a`. – elizzybeth13 Sep 17 '21 at 07:40
  • Do you mean that listA and listB both contain the same items, even if you add new items to listA? I don't see how listB is "in" object A. – ProgrammingLlama Sep 17 '21 at 07:45
  • List of Reference Type does not store actual objects its stores the reference to that object. So if original object changes, same changes reflected in the list. – Shreekesh Murkar Sep 17 '21 at 07:46
  • @Llama There is a line `a.Attribute1=listB;` which indicates there is a `listB` in `a`. No, listA and listB do not contain the same items. In the question, I wrote all the code how I added objects to listA. – elizzybeth13 Sep 17 '21 at 07:52

1 Answers1

4

You can use .ToList() to clone without the need of implement a clonage function.

Example:

a.Attribute1 = listB.ToList();

listA.Add(a); 

Note: you need to using System.Linq; thank to @Matthew Watson

Hachiko001
  • 56
  • 4