8

In all examples when using Roslyn, you have something like this:

SyntaxTree tree = CSharpSyntaxTree.ParseText(
@"using System;
using System.Collections.Generic;
using System.Text;

namespace HelloWorld
{
    // A whole program here...
}");

var root = (CompilationUnitSyntax)tree.GetRoot();

// Getting the semantic model (for MSCORELIB)
var compilation = CSharpCompilation.Create("HelloWorld")
                  .AddReferences(
                     MetadataReference.CreateFromFile(
                       typeof(object).Assembly.Location))
                  .AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);

How to get the semantic model for my code?

The last piece of code retrieves the semantic model for mscorelib types: MetadataReference.CreateFromFile(typeof(object).Assembly.Location) so that I can inspect usings or other parts of the source and get symbol information.

But if I define types in HelloWorld and wanted to retrieve symbol info from those, I would the semantic model. But since I just loaded mscorelib I would not get this info.

How to load the semantic model for the source I just defined?

1 Answer 1

11
static void Main(string[] args)
{
    SyntaxTree tree = CSharpSyntaxTree.ParseText(
        @"using System;

        namespace HelloWorld
        {
            public class MyType{public void MyMethod(){}}
        }"
    );

    var root = (CompilationUnitSyntax)tree.GetRoot();
    var compilation = CSharpCompilation.Create("HelloWorld")
                      .AddReferences(
                         MetadataReference.CreateFromFile(
                           typeof(object).Assembly.Location))
                      .AddSyntaxTrees(tree);
    var model = compilation.GetSemanticModel(tree);
    var myTypeSyntax = root.DescendantNodes().OfType<TypeDeclarationSyntax>().First();
    var myTypeInfo = model.GetDeclaredSymbol(myTypeSyntax);
    Console.WriteLine(myTypeInfo);
}

Is this what you need? myTypeInfo is a type I defined in HelloWorld and I can get is info.

Just to explain, semantic model is something you can get from compilation. Once you have a compilation, you can get all the info from this compilation. Not just from the added reference (mscorlib in your case).

Sign up to request clarification or add additional context in comments.

1 Comment

Precisely what I needed. I was trying something similar, messed up with the API. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.