Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a method's declaring type

Tags:

c#

.net

roslyn

Given a MethodDeclarationSyntax object how can I find out the method's declaring type?

My actual problem is that I need to figure it out whether the referenced method is implementing an interface method or not.

For instance, given the code bellow, if I have a MethodDeclarationSyntax for the Dispose() method, how can conclude it is the implementation of the IDisposable.Dispose()?

using System;
abstract class InterfaceImplementation : IDisposable
{
    public abstract void Dispose();
}

I've tried to get the method's declaring type (and check the type) with no success (Parent property gives me back InterfaceImplementation class).

I also have tried to grab the semantic symbol for the method:

var methodSymbol = (MethodSymbol) semanticModel.GetDeclaredSymbol(methodDeclaration);

but could not spot anything that could help me.

Ideas?

like image 237
Vagaus Avatar asked Feb 17 '12 20:02

Vagaus


1 Answers

Once you have the method symbol, you can ask if a given method is implementing an interface method within a given type. The code is fairly simple:

MethodSymbol method = ...;
TypeSymbol type = method.ContainingType;
MethodSymbol disposeMethod = (MethodSymbol)c.GetSpecialType(SpecialType.System_IDisposable).GetMembers("Dispose").Single();
bool isDisposeMethod = method.Equals(type.FindImplementationForInterfaceMember(disposeMethod));

It's important to note this assumes the type that contains the Dispose method is the type that states it implements IDisposable. In C#, it's possible for a method to implement an interface method that's only stated on a derived type. More concretely, if you ommtted the ": IDisposable" on your code above, and had a derived type of InterfaceImplementation that was IDisposable, that Dispose() method can still implement it.

like image 115
Jason Malinowski Avatar answered Sep 21 '22 08:09

Jason Malinowski