From 19d6d1c2894a130b8ea26963dea86e68bb1f15cf Mon Sep 17 00:00:00 2001 From: DingpingZhang Date: Tue, 2 Apr 2019 11:47:39 +0800 Subject: [PATCH] [Bugfix] Allows the user to return null (default value) when the return value type is a reference type. --- HandyControl/Controls/Other/Dialog.cs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/HandyControl/Controls/Other/Dialog.cs b/HandyControl/Controls/Other/Dialog.cs index cdd81695..16b23909 100644 --- a/HandyControl/Controls/Other/Dialog.cs +++ b/HandyControl/Controls/Other/Dialog.cs @@ -56,12 +56,17 @@ namespace HandyControl.Controls if (!(frameworkElement.DataContext is IDialogResult dialogResult)) throw new InvalidOperationException("The view model of the dialog is not implement the IDialogResult interface. "); - if (!(dialogResult.Result is TResult result)) - throw new InvalidCastException("Could not cast " + - $"the {(dialogResult.Result != null ? $"{dialogResult.Result.GetType()} type" : "null value")} " + - $"to the {typeof(TResult)} type. "); - - return result; + switch (dialogResult.Result) + { + case TResult result: + return result; + case null when !typeof(TResult).IsValueType: + return default(TResult); // The default value of the value type may cause confusion, so should not help the user decide. + default: + throw new InvalidCastException("Could not cast " + + $"the {(dialogResult.Result != null ? $"{dialogResult.Result.GetType()} type" : "null value")} " + + $"to the {typeof(TResult)} type. "); + } } }