How to test if MethodInfo.ReturnType is type of System.Void?


C# Problem Overview

Using reflection to obtain a MethodInfo, I want to test if the type returned is typeof System.Void.

Testing if it is System.Int32 works fine

 myMethodInfo.ReturnType == typeof(System.Int32)


 myMethodInfo.ReturnType == typeof(System.Void)

does not compile? At present Im testing if the string representation of the name is "System.Void" which seems very wrong.

C# Solutions

Solution 1 - C#

You can't use System.Void directly, but can access it using typeof(void).

Several people point out (here and in the comments here for example) that the reason for this is that the ECMA Standard 335, Partition II, section 9.4 says:

> The following kinds of type cannot be > used as arguments in instantiations > (of generic types or methods): > > > - Byref types (e.g., System.Generic.Collection.List 1<string&> > is invalid) > - Value types that contain fields that can point into the CIL > evaluation stack (e.g.,List<System.RuntimeArgumentHandle>) > - void (e.g., List<System.Void> is invalid)

Solution 2 - C#

When I build this, I get the error:

> System.Void cannot be used from C# -- use typeof(void) to get the void type object

Sounds like that's the answer...

Solution 3 - C#


if(methodInfo.ReturnType.Name == "Void"){
  // Your Code.........


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDead accountView Question on Stackoverflow
Solution 1 - C#Jeff SternalView Answer on Stackoverflow
Solution 2 - C#Szymon RozgaView Answer on Stackoverflow
Solution 3 - C#Waleed A.K.View Answer on Stackoverflow