Search code examples
c#cil

C# dynamic method - Field getter with "Object" return type


i need to get the field as type of "object".

This is the IL of the method:

gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, field);
gen.Emit(OpCodes.Ret);

What should i add to cast to object.

Thanks to online C# to IL tools if field was value type i must add

OpCodes.Box

but what if field wasn't value type.

should i get field type and create two seperate dynamic method for reference type fields and value type fields.

Another question :

how can i destroy dynamic method and recreate it. (life cycle?)


Solution

  • You need to box value type results, for instance:

    public void EmitFieldGetter(ILGenerator gen, FieldInfo field)
    {
        gen.Emit(OpCodes.Ldarg_0);
        gen.Emit(OpCodes.Ldfld, field);
    
        if (field.FieldType.IsValueType)
        {
            gen.Emit(OpCodes.Box, field.FieldType);
        }
    
        gen.Emit(OpCodes.Ret);
    }