Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading