6

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

casperOne
  • 73,706
  • 19
  • 184
  • 253
Dennis Larsen
  • 461
  • 4
  • 12

1 Answers1

9

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
Joe Enzminger
  • 11,110
  • 3
  • 50
  • 75
kvb
  • 54,864
  • 2
  • 91
  • 133
  • This works, thx I have over the code here, and simple set method in emit code, can you tell me, why I need to load THIS. When I count, what I think is on the stack, i end op with a This item on the stack, or do I ? Why do I need to load this, Do I need to do it all the time I need to do someting ? – Dennis Larsen Jul 11 '11 at 12:33
  • 1
    @Dennis - if you were writing C#, you'd have something like `this.isDirty = true;`. In IL, it's the same: since you are setting an instance property, you need to indicate which instance you are operating on. The `Stfld` operand will pop both the instance and the value off of the stack when setting the field, so you won't end up with your `this` instance still on the stack. – kvb Jul 11 '11 at 13:37
  • Thx for the clarification, its not easy to do this low level code, but I am getting better at it, as I wrap my brain around this why of coding. – Dennis Larsen Jul 16 '11 at 20:41