Question

This is the first time I'm dabbling with generated CIL, so please bear with my ignorance. I'm looking for a simple DynamicMethod that can read the fields of a POCO, and fill them into an object[]. No type conversion is necessary. I've put together everything I can, can you help complete it?

Type t = typeof(POCO);

DynamicMethod dm = new DynamicMethod("Get" + memberName,typeof(MemberType), new Type[] { objectType }, objectType);
ILGenerator il = dm.GetILGenerator();

// Load the instance of the object (argument 0) onto the stack
il.Emit(OpCodes.Ldarg_0);

// get fields
FieldInfo[] fields = t.GetFields();

// how do I create an array (object[]) at this point?

// per field
foreach (var pi in fields) {

    // Load the value of the object's field (fi) onto the stack
    il.Emit(OpCodes.Ldfld, fi);

    // how do I add it into the array?

}

// how do I push the array onto the stack?

// return the array
il.Emit(OpCodes.Ret);
Was it helpful?

Solution

You can use this code to generate a compiled lambda expression.

public static Func<T, object[]> MakeFieldGetter<T>() {
    var arg = Expression.Parameter(typeof(T), "arg");
    var body = Expression.NewArrayInit(
        typeof(object)
    ,   typeof(T).GetFields().Select(f => (Expression)Expression.Convert(Expression.Field(arg, f), typeof(object)))
    );
   return (Func<T, object[]>)Expression
        .Lambda(typeof(Func<T, object[]>), body, arg)
        .Compile();
}

This is equivalent to the following manually written code:

object[] GetFields(MyClass arg) {
    return new object[] {
        // The list of fields is generated through reflection
        // at the time of building the lambda. There is no reflection calls
        // inside the working lambda, though: the field list is "baked into"
        // the expression as if it were hard-coded manually.
        (object)arg.Field1
    ,   (object)arg.Field2
    ,   (object)arg.Field3
    };
}

This code also produces IL, but instead of you writing it manually, it lets Lambda's Compile method do it for your.

Here is a working demo on ideone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top