Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

c# - What is System.Void?

I know that methods declared with void does not return anything.

But it seems that in C#, void is more than just a keyword, but a real type.
void is an alias for System.Void, like int that is for System.Int32.

Why am I not allowed to use that type? It does not make any sense, but these are just some thoughts about the logic.

Neither

var nothing = new System.Void();

(which says I should use void (Not an alias?))
nor

var nothing = new void();

compiles.

It is also not possible to use something like that:

void GiveMeNothing() { }
void GiveMeNothingAgain()
{
    return GiveMeNothing();
}

So what's the point with System.Void?

question from:https://stackoverflow.com/questions/5450748/what-is-system-void

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the documentation:

The Void structure is used in the System.Reflection namespace, but is rarely useful in a typical application. The Void structure has no members other than the ones all types inherit from the Object class.

There's no reason really to use it in code.

Also:

var nothing = new void();

This doesn't compile for me. What do you mean when saying it "works"?

Update:

A method void Foo() does not return anything. System.Void is there so that if you ask (through Reflection) "what is the type of the return value of that method?", you can get the answer typeof(System.Void). There is no technical reason it could not return null instead, but that would introduce a special case in the Reflection API, and special cases are to be avoided if possible.

Finally, it is not legal for a program to contain the expression typeof(System.Void). However, that is a compiler-enforced restriction, not a CLR one. Indeed, if you try the allowed typeof(void) and look at its value in the debugger, you will see it is the same value it would be if typeof(System.Void) were legal.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...