Tuesday, April 6, 2010

Boxing and Unboxing

Boxing and unboxing act like bridges between value type and reference types. When we convert value type to a reference type it’s termed as boxing. Unboxing is just vice-versa. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.

Below is sample code of boxing and unboxing where integer data type are converted in to object
and then vice versa.

int i = 1;
object obj = i; // boxing
int j = (int) obj; // unboxing


Value types directly contain their data that are either allocated on the stack or allocated in-line in a structure. So value types are actual data.

Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. You can view reference type as pointers to actual data.

Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable. All types derive from the System. Object base type.

No comments:

Post a Comment