Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get extension methods on Roslyn?

Tags:

c#

roslyn

I need to list all extension methods found on the file.

This is what I'm doing so far (looks like it's working):

var methods = nodes.OfType<MethodDeclarationSyntax>();    
var extensionMethods = methods.Where(m => 
        m.Modifiers.Any(t => t.Kind == SyntaxKind.StaticKeyword) 
        && m.ParameterList.Parameters.Any(p => 
            p.Modifiers.Any(pm => pm.Kind == SyntaxKind.ThisKeyword)));

Even though I couldn't test all cases it looks like this is working. But I was wondering if there was a more concise way to approach this solution.

Is there some sort of IsExtension or some SyntaxKind.ExtensionMethod? I took a look but could not find anything obvious, at least.

I'm using the latest Roslyn Sept/12

like image 227
eestein Avatar asked Dec 07 '12 17:12

eestein


1 Answers

You're working at the syntactic level and at this level, there is no such thing as “extension method”. What you can do is to get semantic information (called Symbol) for each method and there you will see whether it is an extension method. Something like:

SyntaxTree tree = …
var compilation = Compilation.Create("foo").AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);

var methods = …
var extensionMethods =
   methods.Where(m => model.GetDeclaredSymbol(m).IsExtensionMethod);

This means your code actually needs to compile and you will also have to add any necessary references to the compilation.

like image 110
svick Avatar answered Oct 05 '22 13:10

svick