Related to How to mutate a boxed struct using IL I am trying to change the value of a boxed value type but in a generic way, so trying to implement the following method:
One solution, is by making an Unbox
method in IL that calls unbox
and returns a ref
to the type contained in the object:
.method public hidebysig static !!T& Unbox(object o) cil managed aggressiveinlining
{
.maxstack 1
ldarg.0
unbox !!T
ret
}
And then using this like:
public static void MutateValueType(object o, T v)
{
ref T ub = ref Unsafe.Unbox(o);
ub = v;
}
This correctly outputs:
var oi = (object)17;
MutateValueType(oi, 43);
Console.WriteLine(oi); // 43
var od = (object)17.7d;
MutateValueType(od, 42.3);
Console.WriteLine(od); // 42.3
NOTE: This requires C# 7 support for ref
returns.
This might be added to say https://github.com/DotNetCross/Memory.Unsafe but it must also be possible with il.Emit
also, so I am looking for that.