Patrick
Patrick

Reputation: 381

programmatically extract interface using roslyn

I am looking for a way to extract an interface from a document (c# class declaration) using Roslyn. going from the reformatter example.

MSBuildWorkspace workspace = MSBuildWorkspace.Create();
// Open the solution within the workspace.
Solution originalSolution = workspace.OpenSolutionAsync(project).Result;

// Declare a variable to store the intermediate solution snapshot at each step.
MSBuildWorkspace workspace = MSBuildWorkspace.Create();
Solution originalSolution = workspace.OpenSolutionAsync(project).Result;
Solution newSolution = originalSolution;
foreach (ProjectId projectId in originalSolution.ProjectIds)
{
    // Look up the snapshot for the original project in the latest forked solution.
    Project proj = newSolution.GetProject(projectId);
    var comp = proj.GetCompilationAsync().Result;
    ///var bind = comp.
    if (proj.Name.EndsWith("Core.DataLayer"))
    {
        foreach (DocumentId documentId in proj.DocumentIds)
        {
            Document document = newSolution.GetDocument(documentId);

            if (IsRepositoryDocument(document))
            {
                //How to implement this?
                var newinterface = GetInterfaceFromRespository(document);
            }
        }
    }
}

I started out using the sample "reformat solution" that the Roslyn team provided. However I am unable to find a public API to extract an interface from a given class file. When trying to find this functionality in the Roslyn source code I can only find internal classes. I found the relevant classes in
"src\Features\Core\Portable\ExtractInterface" of the roslyn source code, i could copy these into my project and get it working, but i would rather not.

TLDR; is there a public API that I can use from C# to extract an interface from a class programatically?

Note that this is done in a "regular" C# project and not in a visual studio extension or analyzer.

Upvotes: 3

Views: 1003

Answers (1)

IMK
IMK

Reputation: 718

You can get all the interfaces from a C# file using the below code statements.

string code = new StreamReader(filePath).ReadToEnd();
var syntaxTree = CSharpSyntaxTree.ParseText(code);
var syntaxRoot = syntaxTree.GetRoot(); 

IEnumerable<InterfaceDeclarationSyntax> interfaceDeclarations = syntaxRoot.DescendantNodes().OfType<InterfaceDeclarationSyntax>();

Then you can iterate the available interfaces in the file.

Upvotes: 3

Related Questions