Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn's GetTypeByMetadataName() and Generic Types

Tags:

c#

types

roslyn

I'm trying to retrieve all the IMethodSymbols within a given type. For closed types (ie. types without generics) I can just use CSharpCompilation.GetTypeByMetaDataName() and pass in the fully qualified type name.

However, with an open type (eg. MyClass<T>) the fully qualified name doesn't seem to work. I've tried supplying the fully qualified name without the type parameter (MyClass), and also with a closed type (MyClass<int>), but neither seems to work.

What's the best way to find this type using its fully qualified name?

like image 238
JoshVarty Avatar asked Jun 11 '14 07:06

JoshVarty


People also ask

Are Roslyn code models immutable?

Roslyn code models are immutable, like working with a .NET string; when you update the string, you get a new string object in return. When you call ReplaceNode, you get back a new root node.

What is the syntaxnodeanalysiscontext in Roslyn?

The SyntaxNodeAnalysisContext, for example, has a CancellationToken that you can pass around. If a user starts typing in the editor, Roslyn will cancel running analyzers to save work and improve performance. As another example, this context has a Node property that returns the object creation syntax node.

What is Roslyn analyzer for immutablearrays?

Roslyn analyzers and code-aware library for ImmutableArrays. The .NET Compiler Platform ("Roslyn") helps you build code-aware libraries. A code-aware library provides functionality you can use and tooling (Roslyn analyzers) to help you use the library in the best way or to avoid errors.

What is gettypebymetadataname in the API?

The API Compilation.GetTypeByMetadataName is not intended as a replacement for using a compiler and the diagnostics the compiler produces. As you've found, there are other APIs that give you the behavior you need.


1 Answers

As mentioned in the comments, the compiler convention is to take a class name like MyClass<T> and represent it as

MyClass`1

A working example:

var tree = CSharpSyntaxTree.ParseText(@"
public class MyClass<T> {
    public static T Method()
    {
    }
}");

var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
       syntaxTrees: new[] { tree }, references: new[] { mscorlib });

var type = compilation.GetTypeByMetadataName("MyClass`1");
like image 111
JoshVarty Avatar answered Oct 23 '22 18:10

JoshVarty