Semantic Model

Other topics

Remarks:

  • Querying the Semantic Model is more costly than querying the Syntax Tree, due to the fact that it most commonly triggers a compilation.

Getting the Semantic Model

There qutie a fiew ways to get the sematic model.

  • From a Document class

    Document document = ...;
    SemanticModel semanticModel = await document.GetSemanticModelAsync();
    
  • From a Compilationclass

    CSharpCompilation compilation = ...;
    var semanticModel = await compilation.GetSemanticModel(syntaxTree);
    
  • From an AnalysisContext. Fro example inside a DiagnosticAnalyzer you can do:

    public override void Initialize(AnalysisContext context)
    {
        context.RegisterSemanticModelAction(x =>
        {
            var semanticModel = x.SemanticModel;
            // Do magical magic here.
        });
    }
    

Get all the references to a method

var syntaxRoot = await document.GetSyntaxRootAsync();

var semanticModel = await document.GetSemanticModelAsync();
var sampleMethodInvocation = syntaxRoot
    .DescendantNodes()
    .OfType<InvocationExpressionSyntax>()
    .First();

var sampleMethodSymbol = semanticModel.GetSymbolInfo(sampleMethodInvocation).Symbol;
var referencesToSampleMethod = await SymbolFinder.FindReferencesAsync(sampleMethodSymbol, document.Project.Solution);

Contributors

Topic Id: 9772

Example Ids: 30100,30101

This site is not affiliated with any of the contributors.