diff --git a/src/Avalonia.Base/Data/BindingValue.cs b/src/Avalonia.Base/Data/BindingValue.cs index 33a893efca..da3f63ae9c 100644 --- a/src/Avalonia.Base/Data/BindingValue.cs +++ b/src/Avalonia.Base/Data/BindingValue.cs @@ -185,6 +185,12 @@ namespace Avalonia.Data return new BindingValue(type | BindingValueType.HasValue, value, Error); } + /// + /// Gets the value of the binding value if present, otherwise the default value. + /// + /// The value. + public T GetValueOrDefault() => HasValue ? _value : default; + /// /// Gets the value of the binding value if present, otherwise a default value. /// @@ -192,6 +198,20 @@ namespace Avalonia.Data /// The value. public T GetValueOrDefault(T defaultValue = default) => HasValue ? _value : defaultValue; + /// + /// Gets the value if present, otherwise the default value. + /// + /// + /// The value if present and of the correct type, `default(TResult)` if the value is + /// not present or of an incorrect type. + /// + public TResult GetValueOrDefault() + { + return HasValue ? + _value is TResult result ? result : default + : default; + } + /// /// Gets the value of the binding value if present, otherwise a default value. /// diff --git a/src/Avalonia.Base/Data/Optional.cs b/src/Avalonia.Base/Data/Optional.cs index 9ad1587194..eae9cc0a2f 100644 --- a/src/Avalonia.Base/Data/Optional.cs +++ b/src/Avalonia.Base/Data/Optional.cs @@ -65,6 +65,12 @@ namespace Avalonia.Data /// public override string ToString() => HasValue ? _value?.ToString() ?? "(null)" : "(empty)"; + /// + /// Gets the value if present, otherwise the default value. + /// + /// The value. + public T GetValueOrDefault() => HasValue ? _value : default; + /// /// Gets the value if present, otherwise a default value. /// @@ -72,6 +78,20 @@ namespace Avalonia.Data /// The value. public T GetValueOrDefault(T defaultValue = default) => HasValue ? _value : defaultValue; + /// + /// Gets the value if present, otherwise the default value. + /// + /// + /// The value if present and of the correct type, `default(TResult)` if the value is + /// not present or of an incorrect type. + /// + public TResult GetValueOrDefault() + { + return HasValue ? + _value is TResult result ? result : default + : default; + } + /// /// Gets the value if present, otherwise a default value. ///