When does Microsoft.Win32.OpenFileDialog.ShowDialog() return null?
Asked Answered
B

3

10

OpenFileDialog's ShowDialog method returns a nullable boolean, set to true if the user clicked OK or false if he clicked Cancel. When does it return null? The documentation does not say.

Brougham answered 11/8, 2009 at 17:43 Comment(4)
"Curiosity" is a perfectly good answer, but I'm curious to know why you ask? Why not just compare what it returns to "true" (TryParse, etc, etc) and roll on?Maice
Just wondering why they use a nullable boolean over a standard one. Comparing against true works fine, as you suggested.Brougham
Now you've got me curious, too. Hopefully someone will come along with a good answer!Maice
Is a nullable boolean returned only by WPF's ShowDialog (and not WinForms')?Maice
M
13

This is stated in the questions linked below, but I'll mention here that Programming WPF (Chris Sells, Ian Griffiths) says:

ShowDialog will always return true or false. ... Only after a dialog has been shown but before it's been closed is DialogResult null.

Similar question: When would ShowDialog() return null?

And: Why is DialogResult a nullable bool in WPF?

Maice answered 11/8, 2009 at 18:5 Comment(0)
D
3

According to the .NET reflector, Microsoft.Win32.OpenFileDialog.ShowDialog is implemented by a base class, Microsoft.Win32.CommonDialog. That implementation has only one return clause:

return new bool?(this.RunDialog(activeWindow));

RunDialog returns a bool, not a bool?.

bool? is just a C# shorthand for System.Nullable<bool>. The constructor of System.Nullable<bool>, according to reflector again, sets the value of the nullable to its parameter, and marks its hasValue property as true.

So... you shouldn't ever get a null result. A quick test confirms that closing the dialog without canceling (red x button) indeed returns a false value, not a null.

The Windows Forms version of OpenFileDialog returns a DialogResult, which has a wider range of values.

Dasya answered 11/8, 2009 at 18:6 Comment(0)
F
1

My guess is that OpenFileDialog returns bool? to be consistent with other WPF dialogs that actually can return a null result.

Finagle answered 12/8, 2009 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.