Roslyn CodeFix Provider (VS2015): How to get a class property/field type

How can I get the data type of a property/field? The only way that I'm able to do that is by searching in the syntax tree of the document where the class is stored. It's a bit slow and there's also the problem of inheritance (Need's to search other file, than another, etc). There's a limitation with my solution: In a solution with multi projects, it need's to have all projects loaded!

Is it possible to do something like:

Type mType = Type.GetType("MyNamespace.SampleClass");

Upvotes: 1

Views: 171

Answers (1)

Matthew
Matthew

Reputation: 29206

You're looking for Compilation.GetTypeByMetadataName.

CodeFixContext context = ...
SemanticModel model = await context.Document.GetSemanticModelAsync();
Compilation compilation = model.Compilation;
INamedTypeSymbol symbol = compilation.GetTypeByMetadataName("MyNamespace.SampleClass");

You can't get a System.Type from a symbol--that's a reflection type, which has nothing to do with Roslyn. You'll have to get by with an INamedTypeSymbol.

Upvotes: 1

Related Questions