Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the CLR know the type of a boxed object?

When a value type is boxed, it is placed inside an untyped reference object. So what causes the invalid cast exception here?

long l = 1;
object obj = (object)l;
double d = (double)obj;
like image 421
fearofawhackplanet Avatar asked Apr 16 '10 09:04

fearofawhackplanet


People also ask

What do you know about boxing and unboxing?

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.

Is the process where the reference type is converted back into a value-type?

The process of converting a Reference Type variable into a Value Type variable is known as Unboxing. It is an explicit conversion process.

Why do we use boxing and unboxing in C#?

Boxing and unboxing is a essential concept in C#'s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object.


2 Answers

No, it's not placed in an untyped object. For each value type, there's a boxed reference type in the CLR. So you'd have something like:

public class BoxedInt32 // Not the actual name
{
    private readonly int value;
    public BoxedInt32(int value)
    {
        this.value = value;
    }
}

That boxed type isn't directly accessible in C#, although it is in C++/CLI. Obviously that knows the original type. So in C# you have to have a compile-time type of object for the variable but that doesn't mean that's the actual type of the object.

See the ECMA CLI spec or CLR via C# for more details.

like image 129
Jon Skeet Avatar answered Oct 05 '22 20:10

Jon Skeet


Jon Skeet's answer covers the why; as for the how to get around it, here's what you have to do:

long l = 1;
object obj = (object)l;
double d = (double)(long)obj;

The reason for the dual cast is this; when .NET unboxes the variable, it only knows how to unbox it into the type it was boxed from (long in your example.) Once you've unboxed it and you have a proper long primitive, you can then cast it to double or any other type castable from long.

like image 26
Adam Maras Avatar answered Oct 05 '22 18:10

Adam Maras