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?
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.
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