I'm new to programming,
As per MSDN,
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit.
I knew We can store any objects in an arraylist, because system.object
is a base for all all types. Boxing and unboxing happens in array list. I agree with that.
Will boxing and unboxing happens in an array? Because We can create object array like below
object[] arr = new object[4] { 1, "abc", 'c', 12.25 };
Is my understanding that boxing and unboxing happens in such array correct?
Every time you assign a value of a value type to a variable of type
object
a boxing operation will occur, So when you do:Which is equivalent to
Three boxes will be created to store 1, 12.25 and 'c' because they are values of value types.
The Array itself is already a reference type, there is no boxing on the array itself. But, as some of your elements are value types (
int
,double
andchar
), and your array type isobject
, a boxing will occur for the said element. When you'll want to extract it, you'll need to unbox it:You can see it in the generated IL:
Yes, value type elements (1, 'c' and 12.25) will be boxed when placed into array of
object[]
.String "abc" will be placed as is since it is reference type object.