-4

I'm creating a little C# apps using List of an object and i have a very noob question :

First i'm filling my object 'A' , then i add in my list named 'lstA' :

List<List<A>> Lst_LstA = new List<List<A>>();  // List of List<A>
List<A> lstA = new List<A>(); // List of my object <A>

A myA = new A();
A.xxx = xx;
A.yyy = yy;

lstA.Add(A);
Lst_LstA.Add(lstA);
lstA.Clear();

What is my problem ? Very simple : When i call lstA.Clear(), it clear my lstA list, perfect, but...it clear too the element in my lst_LstA<> list.

I need to clear the lstA List, but only these list.

Why the Clear() modify too the other list ? How solve this simply ?

Thanks a lot,

best regards,

Walter Fabio Simoni
  • 5,671
  • 15
  • 55
  • 80

1 Answers1

2

The issue is that when you add lstA to lst_lstA, you're adding by reference - i.e. you're just adding a pointer to the list.

The only way for this to work would be to add a copy of lstA to lst_lstA

simonalexander2005
  • 4,338
  • 4
  • 48
  • 92