Array List

  • Thread starter Thread starter Dan
  • Start date Start date
D

Dan

I have an object that I want to add to an ArrayList.
However, I don't know ahead of time how many objects I
will need to add to the list. Therefore, I had built a
function that created an instace of the object, set its
properties, and then added it to the ArrayList. The
function would then adjust the properties of the object
and again add that object to the ArrayList. The problem I
am having is that the changes I make to, what I thought
would be object 2, are also reflected in object 1 when I
retrieve it from the ArrayList. Does the add method of the
ArrayList pass the object by reference or by value? Does
anyone know how to get around this?

Thanks for the help!
 
Hi Dan,
ArrayList saves what you pass to the Add method. If you pass the reference
it will save that reference at some index. If you pass a value then it will
box first the value (because the methods accept parameters of type
Object)and then save a reference to the boxed value. It does not make any
copies of the objects added except in the casses where boxing takes place .

Maybe your function should create a new object each time it has to add a new
object to the list instead just adjust the properties.
Take a look at IClonable interface. But bare in mind that even if you
implement IClonable ArrayList won't use it and will save the reference you
pass to the Add method.

HTH
B\rgds
100
 
Dan said:
I have an object that I want to add to an ArrayList.
However, I don't know ahead of time how many objects I
will need to add to the list. Therefore, I had built a
function that created an instace of the object, set its
properties, and then added it to the ArrayList. The
function would then adjust the properties of the object
and again add that object to the ArrayList. The problem I
am having is that the changes I make to, what I thought
would be object 2, are also reflected in object 1 when I
retrieve it from the ArrayList. Does the add method of the
ArrayList pass the object by reference or by value? Does
anyone know how to get around this?

It doesn't pass the object at all. It passes a reference, and it passes
that by value.

It sounds like you're being confused by the same thing a lot of others
have been in the past, namely the difference between reference types
and value types, and what "pass-by-reference" *really* means.

See http://www.pobox.com/~skeet/csharp/parameters.html
and
http://www.pobox.com/~skeet/csharp/memory.html

for some information which will hopefully help you. It's worth making
sure you really understand this - it's absolutely key to working in
..NET.
 
Back
Top