List<T>.Add() objects which also include a List<T>

Viewed 65

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}); 
1 Answers

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

Related