Question

From MSDN I read that boxing/unboxing is for treating value types as objects. But when I read about ArrayList, it reads that it does boxing as well. So I am quite confused as ArrayList holds value and reference types as objects. Also the following is not unboxing in terms of terminology, its just casting?

ArrayList a=new ArrayList();
a.Add(someClass);

someClass x=(someClass)a[0];
Was it helpful?

Solution

ArrayList performs boxing for value types, but not reference types. Or rather, ArrayList itself doesn't do the boxing - the compiler does. For example:

ArrayList list = new ArrayList();
list.Add(5);

is effectively

ArrayList list = new ArrayList();
object boxed = 5; // Perform boxing from value type type
list.Add(boxed);

Your example is indeed just casting - a reference conversion, not an unboxing conversion. A reference type value doesn't need to be boxed to be stored in an ArrayList - it's already a reference.

Again, that's true of boxing in general, and not specific to ArrayList. Boxing is just a way of using a value type value where you really want a reference... a reference has to be to an object, so the CLR creates an object to wrap the value type value, and returns a reference to that wrapper (the "box" storing the value).

OTHER TIPS

Boxing/unboxing is a feature of the language and the runtime, not a feature of ArrayList. Loosely speaking, it's the conversion of a value type from/to the Object type, and since ArrayList takes in Objects, any value types you pass will be automatically boxed with the box IL instruction.

More specifically, boxing/unboxing involves creating or examining a new object, and copying the data of the value type from the stack to the heap (or vice versa). It's rather expensive, and you'd like to avoid it if possible.

In the case of reference types, no boxing code is normally generated; any unbox instruction that operates on a reference type is, furthermore, simply ignored.

I find it useful to think of value types as being outside the class type system, but regard every value type as having an invisible corresponding reference type derived from ValueType (which in turn derives from Object) which essentially behaves as a class with the same members as Foo, but supports widening casts to and from the real value type.

If a value type is passed to code that expects a derivative of Object, it will be cast to the appropriate invisible reference type; if an object of that reference type is assigned to a variable of the value type, it will be cast back.

BTW, if I had my druthers, there would be some way of specifying that something other than the default casting method should be used, but no such feature exists.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top