Is the object still linked (referenced) after selecting it from the list?

I was wondering and I'm not entirely sure, but help me here.

If you have list items and there is one object, you need to change its property. Let's say myClass has a string property "status". I am looking for my list with a for loop and I get my object, so I do

myClass item = items[i];

      

if i want to change the status property i do it like:

item.Status = "new status";

      

My question / question is this is an "item" still associated with a list item, so if I execute the line above, it also changes in the list without setting this:

items[i] = item;

      

Hope this is clear.

Thanks in advance.

+2


a source to share


4 answers


The code item.Status = "new status";

will change the list item

items[i]

points to the myClass object.

When you say myClass item = items[i];

, it is referred to as the item

, and items[i]

.



so when you change one of the type properties item.Status = "new status";

you are actually making changes to your myClass object, which now has two names item

and items[i]

.

You can also use item[i].Status = "new status";

. Both do the same job.

The setting items[i] = item;

has no effect, since both references are already to the same object.

0


a source


Both the list and the variable item

have references to the actual object. Any changes you make to the object are visible through any link.

In other words, suppose you browse the phone book and select a specific address. You copy the address onto a piece of paper and then drive there. Then you paint the house in red. Now, anyone looking for the same address in the phone book and going there will still see the red house, even though they haven't seen your piece of paper.



Take a look at my article on Value Types and Reference Types for more information.

(This is all assumed to be myClass

indeed a class, by the way.)

+3


a source


Yes, you are changing the item that is in the list. You don't need to reassign it to the list.

+2


a source


Yes, if myClass

is a class that suggests a name (not a structure), this is the type of link . Therefore, it is not copied when you write myClass item = items[i];

. item

is just a reference to the same object as the references items[i]

.

+2


a source







All Articles