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.