tags:

views:

47

answers:

4

Hey guys,

I was wondering, and i'm not really sure, but help me out here.

If you have a List items, and there's one object you need to change a property of it. Say myClass has a string property "status". I'm searching 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 this for example :

item.Status = "new status";

My question/issue is this: is "item" still linked to the list item, so that if i execute the line above, it will be changed in the list as well without having to set this :

items[i] = item;

Hope this is clear.

Thanks in advance.

+2  A: 

Yes, you are altering the item that is in the list. You do not need to assign it to the list again.

Fredrik Mörk
what makes that happen?
djerry
Assuming that myClass is indeed a class and not a struct :-)
Jakob Christensen
@Jakob: it is true even if it is a struct, as long as it is not immutable.
Fredrik Mörk
@Fredrik: I would have to disagree. If myClass is a struct then the item variable will be a copy of the item in the list. In djerry's example item.Status and list[0].Status will not be the same.
Jakob Christensen
@Jakob: of course you are correct and I am wrong :)
Fredrik Mörk
A: 

The code item.Status = "new status"; will change the list item

items[i] points to a myClass object.

When you say myClass item = items[i];, it is referenced by both item and items[i].

so when you alter one of the properties like this item.Status = "new status"; you're 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.

Setting items[i] = item; has no effect, since both reference the same object already.

Veer
+4  A: 

Both the list and the item variable have references to the actual object. Any changes you make to the object are visible through either reference.

To put it another way... suppose you look through the phone book, and pick a particular address. You copy the address onto a piece of paper, and then drive there. You then paint the house red. Now anyone else who looks up the same address in the phone book and goes there will still see a red house, even though they haven't seen your piece of paper.

Have a look at my article about value types and reference types for a bit more information.

(This is all assuming that myClass really is a class, by the way.)

Jon Skeet
+2  A: 

Yes, if myClass is a class as the name suggests (and not a struct) it is a reference type. Therefore it is not copied when you write myClass item = items[i];. item is merely a reference to the same object that items[i] references.

klausbyskov