From 9137cc828ae1f54d71e928ebb1bda67d753e09bc Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Wed, 4 Dec 2019 11:30:29 +0100 Subject: [PATCH] Added overload of GetValueOrDefault that takes no param. To match `Nullable`. --- src/Avalonia.Base/Data/BindingValue.cs | 20 ++++++++++++++++++++ src/Avalonia.Base/Data/Optional.cs | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+) 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. ///