Search code examples
.netreflectionmethodinfo

How can I get fields used in a method (.NET)?


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.


Solution

  • 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:

    static IEnumerable<FieldInfo> GetUsedFields (MethodInfo method)
    {
        return (from instruction in method.GetInstructions ()
               where instruction.OpCode.OperandType == OperandType.InlineField
               select (FieldInfo) instruction.Operand).Distinct ();
    }