Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn: get the symbol for a type defined in a third-party library

Tags:

c#

roslyn

using Roslyn/Microsoft.CodeAnalysis, how can I get the ISymbolfor a third-party type, ie, a type defined in a referenced assembly which is not part of the solution? In my particular case, I'm looking for JSON.NET's JObject, but actually the same question would be valid for BCL stuff like StringBuilder etc.

The only idea I've come up so far is to implement a CSharpSyntaxWalker which looks for all method invocations, property accesses and constructor calls, checks whether they are made on the type I'm interested in and if yes, gets the symbol from the respective SyntaxNode. I'm going to implement this now, but it seems awfully cumbersome. I think there must a better way, but my google-fu has not yielded any relevant results.

Maybe about the background: what I'm trying to do is replace the usage of JObject with the usage of another class.

like image 563
Modern Ronin Avatar asked Oct 27 '15 17:10

Modern Ronin


1 Answers

If you can get access to a Compilation you can call Compilation.GetTypeByMetadataName() and pass in the fully qualified metadata name for the symbol.

Be careful of nested classes and generics, their metadata names are different than they're normal fully qualified names. For more see: Having a "+" in the class name?

Once you have the symbol you can find all usages via SymbolFinder.FindAllReferences()

like image 84
JoshVarty Avatar answered Nov 14 '22 23:11

JoshVarty