Thursday, October 12, 2017

C# Boxing and Unboxing

Boxing in C# means wrapping a value inside an object. Correspondingly, Unboxing is a reverse operation allowing you to extract a value from an object. Value in this case implies a variable of Value Type, not instance of any type as it is in C++ for example. Here is what boxing looks like:

int number = 9;
object obj = number;

As you can see, conversion is implicit. Well, of course, if you want you can do it explicitly:

 int number = 9;
object obj = (object)number;

Unboxing is not as as safe as boxing, that's why you have to do it explicitly:

int number = 9;
object obj = number;
int numberOuttaBox = (int)obj;

Oh, and remember to extract exactly what you previously boxed, because for some reason C# is like real strict about it. Basically what I mean is that you cannot get away with this:

int number = 9;
object obj = number;
float numberOuttaBox = (float)obj;

Such misbehaving is gonna result in getting the following exception:
System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Single'.'

In general, its very easy to bypass it, just unbox what you previously put and then cast to whatever you want either implicitly:

int number = 9;
object obj = number;
float numberOuttaBox = (int)obj;

Or explicitly:

int number = 9;
object obj = number;
float numberOuttaBox = (float)(int)obj; // Excessive, but it's just an example.

Please keep in mind that boxing/unboxing is not casting and excessive use of this operation may severely affect overall performance.

No comments:

Post a Comment