Dennis Larsen
Dennis Larsen

Reputation: 461

emit Opcodes set field to a value

I am trying dynamic create a proxy, so im pleying with Emit. So when I set my field with emit I also need to set a isDirty field boolan to true.

How can I do that ?

Property Customer
{
  set
  {
    this.customerName = value;
    this.isDirty = true;
  }
}

emit code:

 FieldBuilder isDirtyField = myTypeBuilder.DefineField("isDirty", typeof(bool), FieldAttributes.Private);                                                              

// Define the "set" accessor method for CustomerName.
            MethodBuilder custNameSetPropMthdBldr =
                myTypeBuilder.DefineMethod("set_CustomerName",
                                           getSetAttr,
                                           null,
                                           new Type[] { typeof(string) });

        ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();

        custNameSetIL.Emit(OpCodes.Ldarg_0);
        custNameSetIL.Emit(OpCodes.Ldarg_1);
        custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);

        {
            custNameSetIL.EmitWriteLine("Start isDirty");
            ... do stuf here
            custNameSetIL.EmitWriteLine("End isDirty");

        }
        custNameSetIL.Emit(OpCodes.Ret);

This code is working, as long im not trying to do the isDirty field, having spent the weekend on this, im trying to get some help in this forum. thx

// dennis

Upvotes: 6

Views: 4440

Answers (1)

kvb
kvb

Reputation: 55185

I believe that the sequence of IL instructions you want will be

custNameSetIL.Emit(OpCodes.Ldarg_0);     // load this
custNameSetIL.Emit(OpCodes.Ldc_I4_1);            // load true (same as integer 1)
custNameSetIL.Emit(OpCodes.Stfld, isDirtyField); // store into isDirty

Upvotes: 9

Related Questions