c# – Variable assignment error

Question:

The problem is that if I do:

ListaDeListas = {{"1","2","3"},{"4","5","6"},{"7","8","9"}...}

List<string> Lista = new List<string>();

Lista = ListaDeListas[0];

So far so good, that's when after:

Lista.Add("1");
Lista.Add("2");
Lista.Add("3");

Here I check the value of ListaDeListas and it gives me:

ListaDeListas = {{"1","2","3","1","2","3"},{"4","5","6"},{"7","8","9"}...}

I understand that in this code the value of ListaDeListas should remain unchanged but maybe there is something that I am missing or some concept that I have wrong.

Why does this happen?

Answer:

The "strange" behavior you are seeing is actually completely normal!

According to mdsn:

A class is a reference type. When an object of the class is created, the variable to which the object is assigned contains only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made to one variable are reflected in the other variable because they both refer to the same data.

Simplifying .. What does this mean?

Since ListaDeListas an instance of the class List<List<T>> and Lista an instance of List<T> the aforementioned applies completely.

By making the following equality Lista = ListaDeListas[0]; The only thing you are doing is copying the reference to the object, therefore, any modification that the Lista variable undergoes will be directly reflected in ListaDeListas[0] .

What should you do if you want Lista be independent of ListaDeListas ?

You simply copy it, one possibility may be using a loop.

foreach (string s in ListaDeListas[0])
         Lista.Add(s);

Or with Linq you can just use ToList() which does the exact same thing as the loop above, on a single line.

I recommend that you read this mdsn article as well as What are reference types? and What are the types of value? since they are really fundamental concepts.

Scroll to Top