Search code examples
c#.netcompiler-constructionroslyn

Roslyn - Access all used Types within a MethodSymbol


i currently have a IMethodSymbol in access, and now i want to get all used types within this Method. That means

  • The ITypeSymbol of declared, local variables
  • The ITypeSymbol of methodcalls within the given Methodsymbol, which are returing a Type (not System.Void).
  • The ITypeSymbol of all parameters in any methodcall within this method.

The question would be, if roslyn is supporting this which a gracefull API, or if i have to iterate over the syntaxtree and search the information on my own?


Solution

  • This is fairly easy to accomplish with a CSharpSyntaxWalker visiting the method body where you collect the symbols from variable declarations and invocation expressions. While not a one-liner, it should be a fairly short class implementation with two overloaded methods.

    Two things of note: You first need to get the syntax tree from the IMethodSymbol via its DeclaringSyntaxReferences to be able to visit the syntax tree. You can obtain the various symbols from expressions by first getting a SemanticModel for that syntax tree from the Compilation and query it for the respective symbol.