Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to check the type of an expression in Roslyn analyzer?

I'm writing a code analyzer with Roslyn, and I need to check if an ExpressionSyntax is of type Task or Task<T>.

So far I have this:

private static bool IsTask(ExpressionSyntax expression, SyntaxNodeAnalysisContext context)
{
    var type = context.SemanticModel.GetTypeInfo(expression).Type;
    if (type == null)
        return false;
    if (type.Equals(context.SemanticModel.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task")))
        return true;
    if (type.Equals(context.SemanticModel.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task`1")))
        return true;
    return false;
}

It works for Task, but not for Task<int> or Task<string>... I could check the name and namespace, but it's impractical because I have to check each "level" of the namespace.

Is there a recommended way to do it?

like image 480
Thomas Levesque Avatar asked Jan 30 '15 16:01

Thomas Levesque


1 Answers

Check whether the type is a generic type, and, if it is, use OriginalDefinition to return the unconstructed generic type.

like image 164
SLaks Avatar answered Nov 15 '22 23:11

SLaks