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

3

61

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)

but

 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.

Marciamarciano answered 30/11, 2009 at 14:47 Comment(3)
what error are you getting when building that code?Nettlesome
If a method returns Void, it means it does not return anything, so why not reverse the logic and check for what could be returned? Just an idea...Lem
Compiler says "System.Void cannot be used from C# -- use typeof(void) to get the void type". Ah, just read the error. DOH!Marciamarciano
V
82

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)
Vulpine answered 30/11, 2009 at 14:56 Comment(1)
No more hiding the error window! ;) But it is awfully strange.Vulpine
N
20

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

Nettlesome answered 30/11, 2009 at 14:49 Comment(0)
J
-2

Use

if(methodInfo.ReturnType.Name == "Void"){
  // Your Code.........
}
Jerri answered 4/12, 2019 at 17:57 Comment(1)
I can create a class and name it Void, at least check that the Fullname is 'System.Void', still ugly as hellJeremiah

© 2022 - 2024 — McMap. All rights reserved.