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

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?

>Solution :

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.

Leave a Reply