Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare Method ReturnType to Predefined Types

Tags:

.net

roslyn

Using Microsoft Roslyn I am trying to determine if a methods return type is void.
I have the handle on my MethodDeclarationSyntax and can see the property Called "ReturnType" this is a PredefinedType of void. Do I have to actually check the keyword kind? Is there a better way to do this?

((PredefinedTypeSyntax)methodDec.ReturnType).Keyword.Kind() != SyntaxKind.VoidKeyword

Is there a recommended method of accomplishing what I am trying to do?

like image 610
Jay Avatar asked Apr 11 '12 13:04

Jay


1 Answers

For void, that's perfect, since there's no other way to say it. Saying System.Void is explicitly prohibited there.

For other predefined types like int, keep in mind that you can write it either with the keyword or with the .NET type System.Int32. Depending on your scenario, you might actually care to distinguish between them, and so the syntactic check would still be correct. If you don't care about the difference and just want to know if it's an integer, you should then do some binding with a SemanticModel:

var methodSymbol = (MethodSymbol)semanticModel.GetDeclaredSymbol(methodDecl);
if (methodSymbol.ReturnType.SpecialType == SpecialType.System_Int32)
{
    /* ...whatever goes here */
}

MethodSymbol also has a ReturnsVoid property which you might find useful if you happen to have the symbol for it.

like image 145
Jason Malinowski Avatar answered Sep 28 '22 03:09

Jason Malinowski