Teodor Kurtev
Teodor Kurtev

Reputation: 1049

How to check if method parameter type/return type is generic, in Roslyn?

As stated in the title, I want to check if a method params are generic + if the return type of a method is generic.

For example:

    public ISet<string> Collect(MethodDeclarationSyntax method, SemanticModel semanticModel)
    {
        return method
            .ParameterList
            .Parameters
            .Select(x => x.Type.ToString())
            .ToImmutableHashSet();
    }

Here I want to return all the types of the params for the method variable, that are not generic, but I can't find anything in the API to filter the results.

I have the same problem when checking if the return type of a method is generic.

Upvotes: 0

Views: 2535

Answers (1)

Peter Ritchie
Peter Ritchie

Reputation: 35870

It depends on what you have to work with. If you have an ArgumentListSyntax and thus zero or more ArgumentSyntaxes (ArgumentListSyntax.Arguments), you can get the type info from the argument expression:

var type = model.GetTypeInfo(argument.Expression).Type as INamedTypeSymbol;

And from there, the IsGenericType property. For example:

Debug.Assert(type.IsGenericType);

And if you have a MethodDeclarationSyntax object of the method, you can see if the ReturnType property is a type of GenericNameSyntax:

Debug.Assert(methodDeclaration.ReturnType is GenericNameSyntax);

cast to GenericNameSyntax to get more information about the generic type like type arguments.

Upvotes: 3

Related Questions