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?
Check whether the type is a generic type, and, if it is, use OriginalDefinition
to return the unconstructed generic type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With