Qiao Meng
Qiao Meng

Reputation: 1

is there any difference between return void and not return in a void function

Here's the situation: I call a void function in my program, it provide a messagebox with OK and Cancel, but this function is encapsulated. I need to know what the user click on.

So is there anyway I hijack into this function to know the user choice?

Or I think when the programmer write this function, he must return a void when the user click Cancel, and didn't return anything when the user click OK. Is that possible I can differentiated these two actions - return void and not return anything?

I know it seems impossible, but that is why I come to stackoverflow asking you guys.

Thank you

Upvotes: 0

Views: 1099

Answers (2)

Graham Wager
Graham Wager

Reputation: 1887

A function that returns void has only one return - nothing - and so there is no difference between returning nothing or returning void.

If you're unable to change the existing function and all it does is display a MessageBox, I'd scrap it and start again if I were you.

What you want is something like:

public DialogResult GetDialogResult(string message, string caption)
{
    return MessageBox.Show(message, caption, MessageBoxButtons.OKCancel);
}

Call that with the message you want and a caption, and you'll get a return of either DialogResult.OK or DialogResult.Cancel

If it does more than just display the MessageBox, your only option is to check for any change that the function makes if OK is clicked, for example:

  • if a record is added to a database only if OK is pressed, check for that record
  • if the state of the object changes, check for that change:

    OtherObject.SetValueIfOK(2);
    if (OtherObject.GetValue() == 2)
    {
        // OK was clicked
    }
    else
    {
        // Cancel was clicked
    }
    

Anything else and I think you're probably out of luck.

Upvotes: 2

dialer
dialer

Reputation: 4844

"Returning void" (you'd write return;) is exactly the same as returning nothing.

You want to return something like a DialogResult. The .NET framework uses DialogResult.OK and DialogResult.Cancel frequently for what you want to do.

Upvotes: 0

Related Questions