Ritz
Ritz

Reputation: 424

Why change in one list affect other list?

I have two List collection.

List<list<int>> FS = new List<List<int>>();List<List<int> V= new List<List<int>>()

I added some some valuse to FS

Now My FS Look Like

FS={{1},{2},{3}}

Then i assigned valus of FS to V V = FS Now i want to go through each pair

//Performing some Logic 
for (int i = 0; i < FS.Count-1; i++)
        {
            for (int k = i + 1; k < FS.Count; k++)
            {
                List<int> temp = new List<int>();
                temp.AddRange(FS[i]);
                temp.AddRange(FS[k]);
                VF.Add(IP_CFFM(temp));
                V.Add(temp);
                if (IP_CFFM(temp) > IP_CFFM(FS[i]) && IP_CFFM(temp) > IP_CFFM(FS[k]))
                {
                   FS[i].AddRange(FS[k]);
                   FS.Remove(FS[k]);

                }
            }
        }

Before executing if(condition) V will Look Like V = {{1},{2},{3},{1,2}} But after executing the line FS[i].AddRange(FS[k]); List V is changed and it look like {{1,2},{2},{3},{1,2}} Within the if(condition), i am not manipulation or not performing anything on V. Then why it happens?

Upvotes: 0

Views: 1072

Answers (1)

Hari Prasad
Hari Prasad

Reputation: 16956

List<T> is a class, so it is reference.

V = FS actually mean both pointing to same location/address space.

This means that anything you do to it will be reflected in the other. It is just that two different names for your List

Upvotes: 1

Related Questions