Manish Pansiniya's Blog

.NET, C#, Javascript, ASP.NET and lots more…:)

Posts Tagged ‘Unboxing

Boxing & Unboxing in c# (.NET) – Why & What

leave a comment »

This post is just yet another explanation about boxing and unboxing. Before that let us look at just in one line that what is value type and reference type.

Value Type contains actual data and it is stored always on stack. This cannot be null anytime.

Reference Type contains reference/pointer to actual data. Data is stored on heap. This can be null.

Now, as per all the website, boxing is to convert value type to reference type and unboxing is to convert reference type to value type.

But I was thinking, why to convert it from one type to another. The reason I found is, sometimes, you require value type must be passed as reference type e.g. System.Object as parameter. So if you define System.Int32, it allocates 4 bytes to the stack. And if it is passed as System.Object, it is boxed as referenced type and passed to the method. Due to that, System.Int32 behaves exactly same as object. However, in reality, it is just a 4 bytes.

So because of boxing, everything appears as Object (Reference type).

In unboxing, the reference type is converted back to the Value type. But if you look at all the unboxing code, you can find out that explicit cast is required to do the same. That is because CTS need to know whether you are converting the reference type to valid value type due to strict rules.

🙂 Quite Interesting!!!

Written by Manish

April 20, 2009 at 12:13 am