Boxing & Unboxing

Simple types and other structs inherits from ValueType class from System namespace, And as Object class is the base class of all classes also ValueType class inherits from it, if we stop to thinking a little bit that means any simple-type value can be assigned to an Object variable, and that operation called Boxing Conversion, In Boxing Conversion the simple-type value copied into an object so the simple-type value can be manipulated as an object ( Boxing Conversion can be performed either explicitly or implicitly).

int x = 5; //create an int value
object o1 = (int) x; //explicitly box the int value
object o2 = x; //implicitly box the int value

After executing this code both o1 & o2 will refer to two different objects that contain a copy of the integer value, let’s check what happening in the memory.

Now and after we have discussed the Boxing Conversion we can easily explain the Unboxing Conversion as the vice-verse operation of Boxing Conversion which is the explicit conversion of an object reference to a simple-type.

int y = (int) o1;

NOTE: Explicitly attempting to unbox an object reference that does not refer to the correct simple value type causes an InvalidCastException.

Performance
Well let’s talk a little bit about the performance, Boxing and Unboxing are computationally expensive processes, When a value type is boxed an entirely new object must be created this can take up to 20 times longer than a simple reference assignment, And when unboxing the casting process can take four times as long as an assignment.
it’s better to avoid using value types if they will be boxed many times,You can avoid boxing performance problems by using generic collections classes such as List.

Advertisements

3 thoughts on “Boxing & Unboxing

  1. For hottest information you have to pay a quick visit web and on web I found this web site as a finest website
    for most up-to-date updates.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s