1

I have two file as below:

namespace a
{
    Class Audi
    {
            public string Model(string a)
            {           
               Benz obj= new Benz();
               var str=obj.BenzDetails();
               return str;

            }
    }
}
namespace a
{
    Class Benz 
    {
            public string BenzDetails()
            {           
              return "some details";
            }
    }
}

I need to get all objects created in Audi Class (Global or local). Also i need to get details of methods invoked using these declared object.

For example in these 2 classes, for Audi class need:

  • Object created :- obj
  • Method invoked using this object :- BenzDetails
  • name of class whose object is created: Benz
  • namespace of that class: a

I am able to get list of declared objects in a class with this code:

 var lstLocalObjects = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>()
                                                .Where(x => x.Declaration.Variables.Any(p => p.Initializer.Value.Kind().ToString().Equals("ObjectCreationExpression", StringComparison.OrdinalIgnoreCase)));

I have syntax tree, I don't know how to generate Semantic Model. Is it possible to get above details using syntax tree only. Please help. Thank you

1 Answer 1

2

You need to create a Compilation by calling CSharpCompilation.Create(), passing your SyntaxTree and the necessary references (at least mscorlib).

You can then call GetSemanticModel(SyntaxTree).

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

2 Comments

@Gerry, just look at the simple example that create a simple Compilation. For your example just add invocation of GetSemanticModel(SyntaxTree tree, bool ignoreAccessibility) from Compilation
It throws exception : MetadataReference.CreateFromFile(typeof(object).Assembly.Location) Could not load file or assembly 'System.Reflection.Metadata

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.