Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn - Get TypeInfo of type parameter in another TypeInfo

Tags:

c#

roslyn

Starting with a TypeInfo object that represents a generic type, I want to retrieve TypeInfos for each type parameter of the generic type. I would like to expose this as an extension method with this signature:

public static TypeInfo[] GetTypeParameterInfos(this TypeInfo genericType) {
    //Do stuff
}

If I pass in a TypeInfo representing List<int>, it should return an array that contains 1 TypeInfo representing int. If I pass in a TypeInfo represnting Dictionary<int, string>, it should return an array with an int and a string TypeInfo.

Is this possible? How?


Update/Solution:

To clarify, I was asking about Microsoft.CodeAnalysis.TypeInfo, not System.Reflection.TypeInfo. This name confusion has been a real problem in getting meaningful Google results. However, it looks like what I really want is Microsoft.CodeAnalysis.ITypeSymbol, which can be easily acquired from a Roslyn TypeInfo with the TypeInfo.Type property.

The solution is in the INamedTypeSymbol.TypeArguments property, which returns an ImmutableArray<ITypeSymbol> corresponding to the type arguments of the given type symbol.

TypeInfo myGenericType = GetTypeInfoSomehow();
ImmutableArray<ITypeSymbol> typeArguments = myGenericType.Type.TypeArguments;
like image 439
JamesFaix Avatar asked Dec 12 '16 19:12

JamesFaix


1 Answers

As you can see from the source, Roslyn's TypeInfo is a very thin wrapper around ITypeSymbol; that is where you need to look to get anything useful about the type.

If the type is in fact a generic type (as opposed to special types like arrays or pointers), it will actually be an INamedTypeSymbol, which has all the APIs necessary to investigate the type.

In your case, you just want its TypeArguments property.

like image 148
SLaks Avatar answered Sep 19 '22 06:09

SLaks