سؤال

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;
}
هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

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.

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

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.

Just change the method to a boolean and return 0.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top