Search code examples
c#castingboxingunboxing

c# unboxing via object


I can cast byte to int without any problems.

byte a = 2;
int b = a;      // => unboxing, boxing or conversion?

When I cast byte first to object and then to int I get an InvalidCastException.

byte a = 2;
object b = a;    // => boxing?
int c = (int) b; // => unboxing fails?

But I can workaround this problem by using Convert.ToInt32.

byte a = 2;
object b = a;                // => boxing?
int c = Convert.ToInt32(b);  // => what happens here?

  • Why do I get an InvalidCastException in the second example?
  • What does Convert.ToInt32 in the background?
  • Did I label boxing, unboxing and conversion correctly? / What is the correct term when in the examples where I'm not sure?
  • Are the conversion operators at play here? Is there an overview about the basic conversion operators of the basic types?

Please don't hesistate to hint me other things I might have gotten wrong or missed.


Solution

  • Why do I get an InvalidCastException in the second example?

    Because you specified you want to cast (and at the same time unbox) the type of the (boxed) variable to something else. And there is no built-in, implicit or explicit conversion operator defined, so it fails.

    What does Convert.ToInt32 in the background?

    This. It uses the IConvertible interface to do the conversion.

    Did I label boxing, unboxing and conversion correctly? / What is the correct term when in the examples where I'm not sure?

    int b = a;      // => conversion
    object b = a;    // => boxing
    int c = (int) b; // => casting fails
    int c = Convert.ToInt32(b);  // => what happens here: a method call that happens to do a conversion
    

    Are the conversion operators at play here? Is there an overview about the basic conversion operators of the basic types?

    Yes, although defined in the CLR.