I had a question the other day that I ended up taking directly to the Roslyn issues: How do I get a list of all of the types available to a compilation? Schabse Laks (@Schabse) and David Glick (@daveaglick) introduced me to a cool class I hadn’t encountered before: The
In previous posts we touched on the
CSharpSyntaxWalker and the
SymbolVisitor is the analogue of SyntaxVisitor, but applies at the symbol level. Unfortunately unlike the
CSharpSyntaxRewriter, when using the
SymbolVisitor we must construct the scaffolding code to visit all the nodes.
To simply list all the types available to a compilation we can use the following.
In order to visit all the methods available to a given compilation we can use the following:
It’s important to be aware of how you must structure your code in order to visit all the symbols you’re interested in. By now you may have noticed that using this API directly makes me a little sad. If I’m interested in visiting method symbols, I don’t want to have to write code that visits namespaces and types.
Hopefully at some point we’ll get a
SymbolWalker class that we can use to separate out our implemenation from the traversal code. I’ve opened an issue on Roslyn requesting this feature. (It seems like it’s going to be challenging to implement and would require working with both syntax and symbols).
Finding All Named Type Symbols
Finally, you might be wondering how I answered my original question: How do we get a list of all of the types available to a compilation? My implementation is below:
I should note that after implementing this solution, I came to the conclusion that it was too slow for our purposes. We got a major performance boost by only visiting symbols within namespaces defined within source, but it was still about an order of magnitude slower than the simply searching for types via the
SymbolVisitor class is probably appropriate for one-off uses during compilation or for visiting a subset of available symbols. At the very least, it’s worth being aware of.