Lojol
Lojol

Reputation: 653

ArrayList.Add - adds just references?

I am unable to find on MSDN so I am trying here again :) When adding element, its boxed and the reference to new object is added to the collection (if it is value type) or if the element is reference type, just reference is added to arraylist. Is that correct?

EDIT: So it contains just instances of Object class where each one references the value on the heap<

Upvotes: 1

Views: 1130

Answers (5)

Ahmed Samir Hasan
Ahmed Samir Hasan

Reputation: 117

Yes it is, just add a reference.

This is called shallow copy reference. In your case, you must implement a deep copy so you can create a new object and copy your value to it.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273264

Yes it is correct.

ArrayList is not generic (it is from Fx 1.1) and has members like

void Add(System.Object item)  { ... }

So anytime you call Add(x), x has to be converted to a System.Object typed reference. A trivial up-cast for any object reference but Boxing is needed for a value type.

And to join the majority here: You should (almost) never use it anymore. It's only for code that begun before 2005 and maybe for some very rare situation where you want to store mixed types.

Upvotes: 1

Stilgar
Stilgar

Reputation: 23561

Yes it is correct but you should not use ArrayList anyway and stick to generics.

Upvotes: 0

Scott Hyndman
Scott Hyndman

Reputation: 933

Yes. That is correct.

List<> works differently, however.

Upvotes: 0

SLaks
SLaks

Reputation: 887449

That is correct.

In real code, however, you should use generic List<T>s instead of ArrayLists.

Upvotes: 3

Related Questions