ECMA-335, 1.8.2.4, specifies that boxable types include reference types (excluding managed pointers/byrefs) and generic parameters.
What is the purpose of boxing reference types? Is the functionality and memory representation of a boxed reference object any different compare to the unboxed one?
There's nothing logically wrong with boxing a reference type reference. It is just a no-op, nothing changes.
But Ecma-335 isn't always a good description for what is really implemented in the .NET CLR. The JIT_Box() helper function that implements Opcodes.Box will actually throw an InvalidCastException when it is asked to box a value that's not a value type. It expects a compiler and the jitter to know when to suppress the boxing conversion when it is unnecessary. They do.
Consider the generic function:
object MyBox<T>(T value)
{
return (object)value;
}
This compiles to:
ldarg.1
box 01 00 00 1B
ret
The expected behavior of this function is a no-op if T
is a reference type, boxing the value to itself.
Boxing a value that's know to be a reference type is less useful, but specifying it in a way that's consistent with generics is simple and consistent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With