Reflection Emit: Creating Properties

For those who need to create a dynamic type in memory using Reflection.Emit and need to add some properties, here some code for copy-pasting 🙂

The generated code will be equivalent to the following C# code:

public class MyDynamicType
{
    private string _Name;

    public string Name
    {
        get
        {
            return this._Name;
        }
        set
        {
            this._Name = value;
        }
    }
}

And this is the code that generates it:

// Create a Type Builder that generates a type directly into the current AppDomain.
var appDomain = AppDomain.CurrentDomain;
var assemblyName = new AssemblyName("MyDynamicAssembly");
var assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

var typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Class | TypeAttributes.Public);

var propertyName = "Name";

// Generate a property called "Name"

var propertyType = typeof(string);
var field = typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
var propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);

// Generate getter method

var getter = typeBuilder.DefineMethod("get_" + name, GetSetAttr, propertyType, Type.EmptyTypes);

var il = getter.GetILGenerator();

il.Emit(OpCodes.Ldarg_0);        // Push "this" on the stack
il.Emit(OpCodes.Ldfld, field);   // Load the field "_Name"
il.Emit(OpCodes.Ret);            // Return

propertyBuilder.SetGetMethod(getter);

// Generate setter method

var setter = typeBuilder.DefineMethod("set_" + name, GetSetAttr, null, new[] { propertyType });

il = setter.GetILGenerator();

il.Emit(OpCodes.Ldarg_0);        // Push "this" on the stack
il.Emit(OpCodes.Ldarg_1);        // Push "value" on the stack
il.Emit(OpCodes.Stfld, field);   // Set the field "_Name" to "value"
il.Emit(OpCodes.Ret);            // Return

propertyBuilder.SetSetMethod(setter);

This post shows how to call base constructors.

Freelance full-stack .NET and JS developer and architect. Located near Cologne, Germany.

Leave a Reply

Your email address will not be published. Required fields are marked *