Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if method implements interface method marked with attribute

Tags:

c#

roslyn

wcf

Is it possible with Roslyn to figure out if a class method implements some interface method which was marked with attribute?

Particularly in wcf we describe service contracts using interface. Each method of it should be marked with OperationContractAttribute like in following sample

[ServiceContract]
public interface ISimleService
{
    [OperationContract]
    string GetData(int value);
}

public class SimleService : ISimleService
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
}

In Roslyn ISymbol interface provides us GetAttributes() method, but called on a SimleService.GetData() method it returns 0. Called on ISimleService.GetData() declaration it returns OperationContractAttribute as expected.

So in general I have to check class hierarchy to find all interfaces implemented and then traverse hierarchy to find appropriate methods.This is a hard way and I guess there should be an easier one.

like image 279
TOP KEK Avatar asked Dec 24 '22 12:12

TOP KEK


1 Answers

Yes it's possible to find out if a method is an implementation of an interface's method. Here's the code to do that:

methodSymbol.ContainingType
    .AllInterfaces
     .SelectMany(@interface => @interface.GetMembers().OfType<IMethodSymbol>())
     .Any(method => methodSymbol.Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(method)));

You can modify this to actually grab the implemented method, and on that you can check the attributes.

like image 125
Tamas Avatar answered Jan 19 '23 00:01

Tamas