1

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");
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964

1 Answers1

1

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.

Matthew
  • 28,056
  • 26
  • 104
  • 170
  • I only have the Class name, don't have the namespace (may be diferent of the actual one). So to get the SampleClass name space I did: ISymbol mCompleteClassName = compilation.GetSymbolsWithName(x => x == "SampleClass")?.FirstOrDefault(); INamedTypeSymbol symbol = compilation.GetTypeByMetadataName($"{mCompleteClassName}"); Is there a better way? – João Miguel Soares Sep 14 '18 at 14:04
  • If you only have the type name, there could be multiple classes with that name. Your code will be faulty in that case--sometimes selecting the wrong type. You need the fully qualified name of a type in order to uniquely identify it. Can you add some information about what you are trying to accomplish? How did you determine the type name? How will you use the `INamedTypeSymbol`? – Matthew Sep 14 '18 at 20:10