Un Boxing a class object - No Error?

197 views Asked by At

Probably I may be confused with boxing and unboxing.

Consider the following statement from MSDN:

"Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface."

So, this implies that unboxing can only be applied to a value type parameter.

so, this is OK.

var concernedInteger = (int)myObject; //unboxing is ok.

Since class is a reference type, this should not work (because unboxing is only applicable to value type)

var concernedClassObject = (TestClass)testClassObject // unboxing is still ok.

My ReSharper does not show any error.

So, my question is "How can you unbox a reference type variable when MSDN says that only value types can be unboxed" ?

2

There are 2 answers

4
Simon Whitehead On BEST ANSWER

This isn't unboxing. It is type casting.

Unboxing is pulling the value from a reference out into a value type (assuming the cast will succeed). When you're moving reference types around like that.. it's just normal type casting.

Boxing and Unboxing are both types of type casting anyway. The reason they are given special names (boxing and unboxing) is because more goes on in a managed environment rather than just a couple of lookup tables being altered. This is why they are separated into the terms boxing and unboxing for value types.. but when it comes to reference types.. it's just type casting.

1
Rohit On

what you are doing here is TypeCasting not boxing/unboxing. However the same casting syntax is used for both unboxing and explicit reference conversions

Boxing And UnBoxing:

Boxing and unboxing comes into play when you're casting a value type to and from a reference type, basically object

A simple boxing and unboxing example would be like

             int i=1;
             object o=i; /// This is boxing
             int j = (int)o; /// This is unboxing

TypeCasting:

Typecasting causes conversion. A type cast performs an explicit conversion of an expression to a given type.

(type) expression

converts expression to an object of type type. Lets consider example

 long _longval = 1;
 int i = (int)_longval

Explicit casting actually tells the compiler that we know about possible information loss but still we need to perform cast. This is ok for inbuilt Numeric types but it might happen that in reference types it is not at all compatiable .for example

  string _mystring="abc";
  int i=(int)_mystring;

Such casting expressions will compile successfully but they will fail at run-time giving InvalidCastException error.

using As Keyword:

example

  MyClass _MyObject = (MyClass ) obj;
  MyClass MyObject = obj as MyClass ;

When the cast fails at first line of code an exception is thrown whereas in the second line you get only null value.Also you can use as only with reference types so for value types you have to use normal casting method only.