Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to overload ShowDialog() so that a child form returns information as an out parameter?

Tags:

c#

.net

winforms

In an earlier question about how to return a string from a dialog window, yapiskan suggested overloading the child form's ShowDialog() method to include an out parameter.

My question is whether or not this is a good approach in C#.

Here is some example code, based on yapiskan's suggestion. In the child form (in this example, it's a form with a textbox on it), you just need to add the ShowDialog overload and assign UI values to the out parameter:

public DialogResult ShowDialog(out string s)
{
    DialogResult result = this.ShowDialog();
    s = this.textBox1.Text;
    return result;
}

And to show the form and retrieve the entered text, you do this:

using (CustomDialog frm = new CustomDialog())
{
    string s;
    if (frm.ShowDialog(out s) == DialogResult.OK)
    {
        // do something with s
    }
}

One advantage I can think of is that this approach forces the user of the CustomDialog form to get the information it contains through the form's ShowDialog method (rather than from a who-knows-what-it's-called method like GetMyData() or something).

like image 993
MusiGenesis Avatar asked Nov 30 '22 13:11

MusiGenesis


1 Answers

Better to have a Public property/method and get the information.

What would you do if you would need 3..4..5 informations, having 5 parameters out? More clean to have accessors to get your information from the Dialog.

like image 161
Patrick Desjardins Avatar answered May 23 '23 07:05

Patrick Desjardins