You are confusing value boxing with reference casting.
If you do this:
int x = 1;
object a = x;
int i = (int) a;
Then the line object a = x;
is boxing the integer value of x by (effectively) creating a wrapper class that contains the integer value 1
.
When you unbox it by casting it back to int
the runtime code checks that its underlying type is correct (an int
, because you are casting to int
), and then it extracts the underlying value and assigns it to the target int variable.
If you do this:
public class BaseClass
{
}
public class DerivedClass: BaseClass
{
public int Value;
}
...
BaseClass b = new BaseClass();
DerivedClass d = (DerivedClass) b;
int myValue = d.Value; // What would happen? BaseClass doesn't have a Value property!
No boxing is involved here because we are working with reference types. Instead, this code is trying to treat a base class as if it was a derived class.
This is clearly impossible, because for example what would happen if you then tried to access DerivedClass.Value
? This property doesn't exist in the base class, so it's impossible to treat an instance of the base class as a derived class.