Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use SemanticModel.GetSymbolInfo and when SemanticModel.GetDeclaredSymbol

In some cases, when I'm trying to get the the ISymbol for my syntax node, I'm fail (getting null) when using SemanticModel.GetSymbolInfo but succeed when using SemanticModel.GetDeclaredSymbol.

I've attached an example bellow.

So my question is when to use each one of the methods for getting the semantic model?

public class Class1
{
    public System.String MyString { get; set; }

    public static void Main()
    {
        var str =
            @"
            namespace ClassLibrary31
            {
                public class Class1
                {
                    public System.String MyString { get; set; }
                }
            }";

        var syntaxTree = SyntaxFactory.ParseSyntaxTree(str);

        MetadataReference[] metadataReferenceReferences = new MetadataReference[]
        {
            MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
        };

        var compilation =
            CSharpCompilation
                .Create("TraceFluent",
                    new[] {syntaxTree},
                    options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel:1),
                    references: metadataReferenceReferences
                );

        var temp = compilation.Emit("temp");
        var semanticModel = compilation.GetSemanticModel(syntaxTree, true);

        PropertyDeclarationSyntax propertySyntaxNode = 
            syntaxTree.GetRoot()
                .DescendantNodes()
                .OfType<PropertyDeclarationSyntax>()
                .First();

        //var symbolInfo = semanticModel.GetDeclaredSymbol(propertySyntaxNode);
        var symbol = semanticModel.GetDeclaredSymbol(propertySyntaxNode) as IPropertySymbol;
        var typeInfo = semanticModel.GetTypeInfo(propertySyntaxNode).Type;
    }
}
like image 813
Eli Dagan Avatar asked Nov 03 '15 06:11

Eli Dagan


1 Answers

I believe you mean getting the symbol for a given syntax node, and not getting the semantic model for the tree.

Generally, when you want to get the underlying symbol of a declaration (class, property, method, ...), then you should use the GetDeclaredSymbol. Internally, GetSymbolInfo calls this method. You can see the different cases handled there. Declarations are not handled, so for those you'd need to use GetDeclaredSymbol, whose internals you can find here.

like image 163
Tamas Avatar answered Oct 23 '22 17:10

Tamas