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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With