Reputation: 653
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
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
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
Reputation: 23561
Yes it is correct but you should not use ArrayList anyway and stick to generics.
Upvotes: 0
Reputation: 887449
That is correct.
In real code, however, you should use generic List<T>
s instead of ArrayList
s.
Upvotes: 3