Is 'void' a valid return value for a function?

private void SaveMoney(string id...) { ... } public void DoSthWithMoney(string action,string id...) { if(action=="save") return SaveMoney(string id); ... } 

Why does C # not allow me to return the emptiness of a private function through a public function? This is even the same "void" data type ...

Or is the data type not valid?

Is the following code really the shortest workaround?

 if(action=="save") { SaveMoney(string id); return; } 
+6
source share
5 answers

void not the actual type of return (data)! void says no result. Thus, you cannot return a value in a method that declared void , even if the method you call is also declared void .

I have to admit that this will be a good shortcut, but that’s not how everything works :-)


One more thought: if you were allowed, void will become both a data type and the only possible value of this data type, since return x; defined as the return value of x to the caller. So return void; will return void caller - impossible by definition.

This is a different value for null , for example, since null is a valid value for reference types.

+4
source

void not a type in C #. In this case, void means there is no return type or value , so you cannot use it with return , as in the first example.

This is different from C, for example, where void can mean unlimited or unknown type .

+6
source

This is not a workaround, this is the right way to do it.

+4
source

Even if this compiled, I would not recommend it. In such a small method, it’s clear what is happening, but if it is a larger method, the next programmer will see that, blinking, think that “I thought it was an invalid method”, scroll up, confirm that scroll back, follow the SaveMoney method , find out that it returns nothing, etc.

Your workaround makes this clear at a glance.

+4
source

Just change the method to boolean and return 0.

+1
source

All Articles