Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MethodBody of Lambda change after invocation?

Tags:

c#

lambda

I was wondering if someone could explain this to me. For some reason the MethodBody of a lambda seems to change after invocation.

The following code snippet makes a simple lambda with one outer variable and examines the method body.

    int x = 7;
    Func<int> f = () => x;

    int before = f.Method.GetMethodBody().GetILAsByteArray().Length;
    f();
    int after = f.Method.GetMethodBody().GetILAsByteArray().Length;

In this case the length before invocation is 11 bytes and after invocation is 126.

ILDASM shows the lambda body in the DLL (before case) as 11 bytes with the expected IL:

  IL_0000:  ldarg.0
  IL_0001:  ldfld      int32 Tests.LambdaTest::x
  IL_0006:  stloc.0
  IL_0007:  br.s       IL_0009
  IL_0009:  ldloc.0
  IL_000a:  ret

I have not had time to try and disassembled the 'after' case as (presumably) I will have to extract the IL at run-time to feed into a disassembler. I do know it does contain the relevant ldfld. Probably if I did go to the trouble it may be obvious (?)

This is not critical for me, just interested to understand what is going on.

regards,

Andrew

like image 245
user3089846 Avatar asked Nov 02 '22 09:11

user3089846


1 Answers

Found it.

Seems to be the code weaver in Telerik JustMock.

If I disable the add-in altogether then the MethodBody does not alter.

Caught me a little by surprise as I am not actually using any mocks in these projects. I will have to check the doco to understand what (if anything) the JustMock add-in may be doing by default.

Thanks again to the quick responders, as they highlighted the fact that it was environmental in some way.

like image 81
user3089846 Avatar answered Nov 10 '22 20:11

user3089846