Why boxing link types?

ECMA-335, 1.8.2.4, indicates that box types include reference types (excluding managed byrefs) and general parameters.

What is the purpose of reference box types? Is the boxed representation of the functionality and memory of an object compared to an unrelated one?

+6
source share
2 answers

In boxing, a reference to a reference type is nothing logically incorrect. It's just non-op, nothing changes.

But Ecma-335 is not always a good description of what is really implemented in the .NET CLR. The helper function JIT_Box (), which implements Opcodes.Box, will actually throw an InvalidCastException when it is prompted to introduce a value that is not a value type. He expects the compiler and jitter to know when to suppress box conversion when it is not needed. They make.

+5
source

Consider the general function:

object MyBox<T>(T value) { return (object)value; } 

Compiled for:

 ldarg.1 box 01 00 00 1B ret 

The expected behavior of this function is no-op if T is a reference type, boxing a value for itself.

Boxing - a value that is known as a reference type, is less useful, but specifying it in such a way that, according to generics, is simple and consistent.

+3
source

Source: https://habr.com/ru/post/956582/


All Articles