Search code examples
c#castingboxingunboxing

Boxing/unboxing - only value types? Ref.types - casting?


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];

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).