0

in the following code I want to get the dialog result of a Form but it's not saved to my variable... why?

My code:

public void xyz() {
    var dialogResult = new DialogResult();
    if (booleanVariable) {
        var form1 = new Form1();
        form1.ShowDialog();
        dialogResult = form1.DialogResult;
    }
    else {
        var form2 = new Form2();
        form2.ShowDialog();
        dialogResult = form2.DialogResult;
    }

    if (dialogResult == DialogResult.OK) {
        ...
    }
}

At the and of my Form1 and Form2 i set the this.DialogResult = DialogResult.OK. At the end of the process my variable dialogResult is DialogResult.None, why?

kyjan
  • 291
  • 1
  • 4
  • 11
  • `var dialogResult = new DialogResult();` is a bit strange. The `DialogResult` type is an enumeration. You shouldn't need to use `new` at all. – Cody Gray - on strike Jan 07 '12 at 11:58
  • Cody: This may be the attempt at correct typing due to `var`. It seems like they don't know how to declare variable types explicitly. – Joey Jan 07 '12 at 12:06
  • No this is a attempt to declare the variable globaly because i can't acces it if I declare it within the if. – kyjan Jan 07 '12 at 12:10
  • 1
    That's non-responsive to the issue. You can't use `var` to declare a variable unless you're assigning to it at the same time because otherwise the static type cannot be deduced. Since there's no reason to `new` an enum type, you can't use `var` to declare it. Just write: `DialogResult dialogResult;` – Cody Gray - on strike Jan 07 '12 at 12:23
  • Ok I recognized my fault :) thank you guys – kyjan Jan 07 '12 at 12:31

2 Answers2

1
public void xyz() {
    var dialogResult = booleanVariable ? new Form1().ShowDialog() : new Form2().ShowDialog();

    if (dialogResult == DialogResult.OK) {
        ...
    }
}
kyjan
  • 291
  • 1
  • 4
  • 11
Ali Foroughi
  • 4,540
  • 7
  • 42
  • 66
1

try to modify this with your IF Statement:

DialogResult var;
Form2 qwerty  = new Form2();
var = qwerty.ShowDialog();
MessageBox.Show(var.ToString());
John Woo
  • 258,903
  • 69
  • 498
  • 492