Home > OS >  If I reference List A to List B, I do changes on List B, would it affect List A?
If I reference List A to List B, I do changes on List B, would it affect List A?

Time:11-08

I have a list called ListA: List<string> allStuffs = ...

I want to reference the list to ListB as List<string> secondList = allStuffs;

If I do something like secondList.Remove(someitem), would it also remove the same item on allStuffs?

CodePudding user response:

Yes; there is only one list object in this example - whatever the ... is on the first line. The List<string> secondList = allStuffs; doesn't create a new list - it just creates a new reference, with the value copied from allStuffs - which is itself just a reference (not the list itself).

You can have as many references to that list object as you like: they're all just indicators as to where the actual list is.

So if you follow one copy of the reference to the object to call Remove, the change will be visible from any other reference to the same object.

CodePudding user response:

Yes as explained in the above answer it is pointing to the same list. if you don't want to change the first list on change anything on the second then you can use it like this.

List<int> ls1 = new List<int>() { 1, 2, 3 };
List<int> ls2 = new List<int>(ls1);
ls2.Remove(1);

ls1 will still have 1,2 and 3

  • Related