none
How to get method variables with reflection RRS feed

  • Question

  • I built a scripting application with a code editor that has an intelli-sense like feature.

    Using reflection I can perfectly get types, properties, methods and fields.

    However, I can't find a way to get variables' name and type declared inside a method and I wonder if it was possible at all with reflection ? Apparently MethodInfo returned by GetType.GetMethod() does not deliver this functionality.

    Any ideas please ?

    Friday, February 5, 2016 1:58 PM

Answers

  • That's not going to work, local variables do not exist in assembly metadata. IL does have the notion of local variable but those do not map directly to C# local variables - some C# locals may simply not exist in IL, multiple C# locals may be mapped to the same IL local, information about local scopes and names is missing etc.

    What you're trying to do isn't usually done by using reflection. You need a language parser to obtain this kind of information. Have a look at Roslyn perhaps.

    • Marked as answer by Lac Sunday, February 7, 2016 12:47 PM
    Friday, February 5, 2016 6:59 PM
    Moderator
  • As Mike says, local variable names are not stored in the assembly. But If you have access to the pdb files, then you can use the Diagnostics Symbol Store API to extract them.

    ISymUnmanagedBinder => ISymUnmanagedReader => ISymUnmanagedMethod => ISymUnmanagedScope => ISymUnmanagedVariable

    There are managed wrappers for this API, but I have always preferred to just use the COM API directly.

    • Marked as answer by Lac Sunday, February 7, 2016 12:47 PM
    Friday, February 5, 2016 11:38 PM

All replies

  • That's not going to work, local variables do not exist in assembly metadata. IL does have the notion of local variable but those do not map directly to C# local variables - some C# locals may simply not exist in IL, multiple C# locals may be mapped to the same IL local, information about local scopes and names is missing etc.

    What you're trying to do isn't usually done by using reflection. You need a language parser to obtain this kind of information. Have a look at Roslyn perhaps.

    • Marked as answer by Lac Sunday, February 7, 2016 12:47 PM
    Friday, February 5, 2016 6:59 PM
    Moderator
  • As Mike says, local variable names are not stored in the assembly. But If you have access to the pdb files, then you can use the Diagnostics Symbol Store API to extract them.

    ISymUnmanagedBinder => ISymUnmanagedReader => ISymUnmanagedMethod => ISymUnmanagedScope => ISymUnmanagedVariable

    There are managed wrappers for this API, but I have always preferred to just use the COM API directly.

    • Marked as answer by Lac Sunday, February 7, 2016 12:47 PM
    Friday, February 5, 2016 11:38 PM
  • Thanks guys for the useful answers, I will look into both solutions suggested.
    Sunday, February 7, 2016 12:48 PM