Alexander
Alexander

Reputation: 20244

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 won't C# let me return the void of the private function back through the public function? It even is the same data type "void"...

Or isn't void a data type?

Is the following code really the shortest workaround?

if(action=="save") {
    SaveMoney(string id);
    return;
}

Upvotes: 7

Views: 9755

Answers (5)

sootie8
sootie8

Reputation: 46

Just change the method to a boolean and return 0.

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

void is not an actual return (data)type! void says there is no result. So you can not return a value in a method that's declared void even though the method you're calling is also declared void.

I must admit it would be a nice shortcut, but it's not how things work :-)


Just an additional thought: If what you want was allowed, void would become both a data type and also the only possible value of that data type, as return x; is defined as returning the value x to the caller. So return void; would return the value void to the caller - not possible by definition.

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

Upvotes: 5

Mikey Mouse
Mikey Mouse

Reputation: 3098

Even if this would compile I wouldn't recommend it. In such a small method, it's clear what's going on, but if it's a bigger method, the next programmer is going to see that, blink, think "I thought this was a void method" scroll up, confirm that, scroll back down, follow the SaveMoney method, find out it returns nothing, etc.

Your "workaround" makes that clear at a glance.

Upvotes: 4

akton
akton

Reputation: 14386

void is not a type in C#. In this instance, void means the absence of a return type or value so you cannot use it with return as you have in the first example.

This is different to C, for example, where void can mean typeless or an unknown type.

Upvotes: 6

meilke
meilke

Reputation: 3280

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

Upvotes: 4

Related Questions