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?
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.
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