In .NET, using reflection how can I get class variables that are used in a method?
Ex:
class A
{
UltraClass B = new(..);
SupaClass C = new(..);
void M1()
{
B.xyz(); // it can be a method call
int a = C.a; // a variable access
}
}
Note: GetClassVariablesInMethod(M1 MethodInfo) returns B and C variables. By variables I mean Value and/or Type and Constructor Parameters of that specific variable.
Reflection is primarily an API for inspecting metadata. What you're trying to do is inspect raw IL which is not a supported function of reflection. Reflection just returns IL as a raw byte[] which must be manually inspected.
Here's a complete version of the correct answer. This uses material from other answers, but incorporates an important bugfix which no-one else spotted.
@Ian G: I have compiled the list from ECMA 335 and found out that I can use
And the opcode length list is here, if anyone needs it:
There's a lot of different answers, but as not a single one appeals to me, here's mine. It's using my Reflection based IL reader.
Here's a method retrieving all the fields used by a method:
You need to get the MethodInfo. Call GetMethodBody() to get the method body structure and then call GetILAsByteArray on that. The convert that byte array into a stream of comprehensible IL.
Roughly speaking
where OpCodeList is constructed via
You can then work out which instructions are IL property calls or member variable look ups or whatever you require and resolve then via GetType().Module.ResolveField.
(Caveat code above more or less work but was ripped from a bigger project I did so maybe missing minor details).
Edit: Argument size is an extension method on OpCode that just uses a look up table to do find the appropriate value
You'll find sizes in ECMA 335 which you'll also need to look at for the OpCodes to find which OpCodes you to search for to find the calls you are looking for.