Using Roslyn to get a list of Implemented Interfaces for CSharpSyntaxRewriter

Standard

While working on a project to update method signature’s and add a parameter down the entire stack I ran into an issue when the method being altered is implemented as part of an interface, as the implementing class no longer matches the interfaces signature. Because of this I needed to get a collection of the implemented interfaces for the class beforehand which was not straightforward.

The information needed is available from INamedTypedSymbol for the class. This is obtained through the SemanticModel using the GetDeclaredSymbol method. Once you have this Symbol the interfaces are available through the AllInterfaces property.

    public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        var tree = node.SyntaxTree;
        var root = tree.GetRoot();   
        // Get the Semantic Model         
        var sModel = comp.GetSemanticModel(node.SyntaxTree);
        // Get symbol for the class
        var classSymbol = sModel.GetDeclaredSymbol(root.DescendantNodes().OfType<ClassDeclarationSyntax>().First());
        // Get classes implemented interfaces.
        var implementedInterfaces = classSymbol.AllInterfaces;

        return base.VisitClassDeclaration(node);
    }