How to get various types used in a C# project with Roslyn

565 Views Asked by At

I am analyzing about converting an existing C# library to java. To start with I need to know what are the types / built-in keywords used in the existing C# library. I mean, for example

public class CSharpClass
{
int i;
float j;
Console.Writeline(String.Concat("A","B"));
}

In this class the types/Keywords used are,

  1. public
  2. int
  3. float
  4. Console
  5. String

My Questions are,

  1. Is there any way to do this. I hope I can do this with Roslyn. But we can get “LocalDeclarationStatementSyntax” for variables. But how to parse “Console” and “Concat”. Is that “Sytax walker” that parses all the tokens in a class is the only option?
  2. Also how to get all the classes from a project file with Roslyn?
1

There are 1 best solutions below

0
On

You need to semantics as well -- syntax is just the text you see and that's exactly what you get, nothing more, nothing less. Get a Compilation for your project, then you can call GetSemanticModel where you give it a tree, and then from there you can call GetTypeInfo or GetSymbolInfo (as appropriate, search online for the difference between these two) to get type information.

As far as getting the Compilation, if you're writing a command line tool you probably want to use MSBuildWorkspace to load your project. If you're analyzing the projects open in Visual Studio, use VisualStudioWorkspace, etc.