Check C # Action / Lambda / Delegate contains any codes / statements

Can someone tell me if there is a way to see if the action contains any code?

Action x = new Action(()=> { }); 

should return false, and

 Action x = new Action(()=> { var x = "i am a string" }); 

should return true.

Perhaps using reflection?

+4
source share
1 answer

Perhaps this will help:

  Action x = new Action(() => { var xx = "i am a string"; }); Action x1 = new Action(() => { }); MethodBody mb = x.Method.GetMethodBody(); MethodBody mb1 = x1.Method.GetMethodBody(); byte[] b = mb.GetILAsByteArray(); byte[] b1 = mb1.GetILAsByteArray(); 

b1 (empty method body) has only 2 bytes, values ​​0 and 42 mean nop and return , I think.

+7
source

All Articles