Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why boxing reference types?

Tags:

c#

.net

clr

boxing

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?

like image 292
user2341923 Avatar asked Oct 23 '13 18:10

user2341923


2 Answers

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.

like image 126
Hans Passant Avatar answered Sep 22 '22 11:09

Hans Passant


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.

like image 24
CodesInChaos Avatar answered Sep 22 '22 11:09

CodesInChaos