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?
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)
Perhaps because if System.Void were allowed as a type reference, it might start appearing in
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
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