DanceWithWolf

Have a dumb question that I would like some help with...I have a collection of objects of type foo. I want to replace (update) one of the objects in the collection.

I've passed the routine a new Foo object newFoo1

Why is this:
for (int i=0; i<BunchofFoos.Count;i++)
{
.....
Foo foo=BunchofFoos[ i ];
foo=newFoo1;
}

different from
for (int i=0; i<BunchofFoos.Count;i++)
{
.......
BunchofFoos[ i ]=newFoo1;
}



Re: Visual C# General Simple object assignment question

houtexwebdev

depends on the type of collection you have. I'm going to guess, if this is not an array, that you'll have Remove(index) and Insert(index,Object) methods. Possible a SetItem(index,object) method.



Re: Visual C# General Simple object assignment question

Derek Smyth

Hi,

Not a dumb question at all. It is to do with referencing. When you say an object1 = object2 your setting a reference, its like saying object 1 references object2. Both object point to the same object in the managed heap, they both point to the same memory location. Update one and the other updates. If your familiar with pointers then you know this is.

When you do... Foo foo = BunchOfFoos[ i ] ... you are saying the foo object references the BunchOfFoosIdea object. When you then say... foo = newFoo1 then your changing foo's reference to no longers point to BunchOfFoos[ i ] object but to another object. Your pointing the reference to another object.

foo -> BunchOfFoos[ i ] then foo->newFoo1

With the other example, your not doing that. Instead your pointing BunchOfFoos[ i ] to the newFoo1 object.

BunchOfFoos[ i ] -> newFoo1

That made perfect sense when I wrote it, hopefully it made sense when you read it.






Re: Visual C# General Simple object assignment question

DanceWithWolf

Obvious (once you explained it!) Big help.

Thanks.