ChaseMedallion
ChaseMedallion

Reputation: 21794

How to explore an API like System.Reflection in Roslyn?

Using System.Reflection, it's easy to explore all of the various types in an assembly, drilling down into their members, properties, etc. What (if any) is the comparable API for doing this in Roslyn?

Upvotes: 1

Views: 429

Answers (1)

JoshVarty
JoshVarty

Reputation: 9426

There are some helpful Roslyn snippets on the FAQ.

For the question:

How do I get all symbols of an assembly (or all referenced assemblies)

The following is provided. It simply prints all the namespaces, types, fields and methods in all the assemblies referenced by your compilation. This should act as a good starting point for you.

var compilation = ... //Get a compilation
var results = new StringBuilder();

// Traverse the symbol tree to find all namespaces, types, methods and fields.
foreach (NamespaceSymbol ns in compilation.GetReferencedAssemblySymbol(mscorlib).GlobalNamespace.GetNamespaceMembers())
{
    results.AppendLine();
    results.Append(ns.Kind);
    results.Append(": ");
    results.Append(ns.Name);
    foreach (var type in ns.GetTypeMembers())
    {
        results.AppendLine();
        results.Append("    ");
        results.Append(type.TypeKind);
        results.Append(": ");
        results.Append(type.Name);
        foreach (var member in type.GetMembers())
        {
            results.AppendLine();
            results.Append("       ");
            if (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Method)
            {
                results.Append(member.Kind);
                results.Append(": ");
                results.Append(member.Name);
            }
        }
    }
}

Upvotes: 1

Related Questions