Search code examples
c#emit

Emit and set Property


I would like to Emit a Property and set it:

var pb = tb.DefineProperty("myProp", PropertyAttributes.None, typeof(object), Type.EmptyTypes);
IL.Emit(OpCodes.Newobj, typeof(object).GetConstructor(Type.EmptyTypes));
IL.Emit(OpCodes.Call, pb.SetMethod);

but the pb.SetMethod is null at that point - what am I missing here?


Solution

  • Looking at the documentation for DefineProperty, you still need to define the setter (and getter) methods yourself. This is the part relevant to a set method, but you'll probably need to do the get method too:

    // Backing field
    FieldBuilder customerNameBldr = myTypeBuilder.DefineField(
        "customerName",
        typeof(string),
        FieldAttributes.Private);
    
    // Property
    PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty(
        "CustomerName",
        PropertyAttributes.HasDefault,
        typeof(string),
        null);
    
    // Attributes for the set method.
    MethodAttributes getSetAttr = MethodAttributes.Public |
                                  MethodAttributes.SpecialName |
                                  MethodAttributes.HideBySig;
    
    // Set method
    MethodBuilder custNameSetPropMthdBldr = myTypeBuilder.DefineMethod(
        "set_CustomerName",
        getSetAttr,     
        null,
        new Type[] { typeof(string) });
    
    ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();
    
    // Content of the set method
    custNameSetIL.Emit(OpCodes.Ldarg_0);
    custNameSetIL.Emit(OpCodes.Ldarg_1);
    custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
    custNameSetIL.Emit(OpCodes.Ret);
    
    // Apply the set method to the property.
    custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);