In short, I think boxing is a nuisance. Let's look at some alternatives ...
public class Box<T>
where T : struct
{
public T Value { get; set; }
public static implicit operator T(Box<T> box)
{
return box.Value;
}
}
System.Int32 comes from the abstract System.ValueType class, which comes from the System.Object class. You cannot get from System.ValueType in C #, but I would suggest that the struct keyword does just that, and the CLI recognizes these types of type definitions as having pass-by-value semantics. Anyway, when a struct is assigned an object type, boxing occurs. I donβt want to get into boxing as such, instead I want to get straight to it.
I looked at the part of the IL generated by the C # compiler.
object obj = 1;
.locals init ([0] object obj)
L_0000: nop
L_0001: ldc.i4.1
L_0002: box int32
L_0007: stloc.0
Found this on MSDN ...
A value type has two separate representations within a common language infrastructure (CLI):
"raw", , .
A 'boxed' form, ( ) , .
, , ...
var box = obj as Box<int>;
if (box != null)
{
Console.WriteLine(box.Value);
}
System.Object, , unbox box ValueType ? , , - ?
- - ? , , - , , . -. , ValueType ( 8 ), "ReinterpretCast".
[StructLayout(LayoutKind.Explicit)]
public struct ReinterpretCast
{
[FieldOffset(0)] sbyte @sbyte;
[FieldOffset(0)] byte @byte;
[FieldOffset(0)] short @ushort;
[FieldOffset(0)] ushort @short;
[FieldOffset(0)] int @int;
[FieldOffset(0)] uint @uint;
[FieldOffset(0)] long @long;
[FieldOffset(0)] ulong @ulong;
[FieldOffset(0)] float @float;
[FieldOffset(0)] double @double;
}