Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not System.Void? [duplicate]

Tags:

c#

.net

Possible Duplicate:
What is System.Void?

I have no practical reason for knowing this answer, but I'm curious anyway...

In C#, trying to use System.Void will produce a compilation error:

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

As I understood it, void is simply an alias of System.Void. So, I don't understand why 'System.Void' can't be used directly as you might with 'string' for 'System.String' for example. I would love to read an explanation for this!

Incidentally, System.Void can be successfully used with the Mono compiler, instead of Microsoft's, and there it appears equivalent to using the void keyword. This must therefore be a compiler-enforced restriction rather than a CLR restriction, right?

like image 630
Stewart Avatar asked Jun 20 '11 08:06

Stewart


2 Answers

I believe the sole purpose for this struct is to use it in reflection, whereas the other types (like System.String, System.Int32 etc.) are proper types holding data. Void carries no data and you cannot instantiate this struct from your code.

My guess about the compiler error is that it's there to enforce consistency in code. It would look weird to have methods like this:

System.Void MyMethod() { ... }

At first glance, it appears to be returning something while in reality it doesn't. In my opinion, this is a good decision by the C# team (if my speculation about it is correct)

like image 85
Isak Savo Avatar answered Nov 17 '22 15:11

Isak Savo


Perhaps because if System.Void were allowed as a type reference, it might start appearing in

  • function declarations (return type) -- this is obviously legit
  • parameter declarations
  • template argument declarations
  • variable declarations

Using typeof(void) makes that syntactically illegal. This follows the principle of least surprise

Edit Also, as Eric Lippert points out, it is because, e.g. Void is not a superclass of anything (void is, in fact, invariant). Read all about it here https://learn.microsoft.com/en-us/archive/blogs/ericlippert/the-void-is-invariant

like image 27
sehe Avatar answered Nov 17 '22 13:11

sehe