I have written some code in a WPF application, which looks like this:
var dialog = new OpenFileDialog { Filter = this.FileExtensionFilter };
var dialogResult = dialog.ShowDialog();
if (dialogResult.HasValue && dialogResult.Value)
{
... Process result of dialog ...
}
All well and good, I thought, but ReSharper has come up with a warning on the check for dialogResult.HasValue
, "Expression is always true".
The first question is how ReSharper would even know that the dialogResult always has a result - it must have dived right down into the decompiled code of the Microsoft.Win32.OpenFileDialog
class and observed that it never returns null. Either that, or it's just a hardcoded warning specifically for this class.
Secondly, it doesn't seem like good practice to just assume that the result will never be null. What if Microsoft release a future version of the library in which the null value does become available? The documentation on the matter says: "In the current implementation, the derived classes (OpenFileDialog and SaveFileDialog) will only return true or false" which does imply this is not a permanent arrangement that we can rely on forever.
Any thoughts on whether I'm being overcautious and should remove the line as ReSharper suggests?
It does seem odd. The MSDN spec states that it will return either true or false, but still there must be a reason for the Nullable.
I would absolutely agree with you, that assuming an implementation underneath is bad practise. I would code as per the interface, so in this case I think checking the HasValue is the correct way to go.
How does Re-sharper know? I'm afraid I can't answer that. It's not something I use, they may have hard-coded it.
This may be of interest to you: When does Microsoft.Win32.OpenFileDialog.ShowDialog() return null?
It seems the reason there is the possbility of null is because that's the result before the user has closed the dialog.