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 an item from one list is added to another List – are they referencing the same object?

In C#, I am wondering about the following scenario. I have the following list declared in myCurrentClass

private List<someOtherClass> mySteps = new List<someOtherClass>();

Suppose there is also another List in my class that can hold object of type someOtherClass as well. I don’t know how to fully explain this other than saying the library I’m working with provides a property that is a list of objects and it can accept derived types into that list such as my someOtherClass. Let’s call this other list that is provided by the library secondList

Now in the constructor of myCurrentClass I do the following:

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

for (int i = 0; i < MAX_STEPS; i++)
{
        mySteps.Add(new someOtherClass());
        secondList.Add(mySteps[i])
}

My question is, is mySteps[i] and secondList[i] referring to the same object? So if somewhere later in the execution of myCurrentClass I do something like this:

mySteps[i].someValue = 13;

then SecondList[i].some value will also equal 13?

>Solution :

I don’t know why you want to make this but yes, they are the same object (instance) of someOtherClass. That is because when you call secondList.Add(mySteps[i]), you will refer to the same (already existing) object mySteps in secondList.
So: mySteps[i].someValue = 13; secondList[i].someValue is also 13.

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