diff --git a/Base.Tests/Structures/MaybeExtensionTests.cs b/Base.Tests/Structures/MaybeExtensionTests.cs index a1cdf54..cf817d6 100644 --- a/Base.Tests/Structures/MaybeExtensionTests.cs +++ b/Base.Tests/Structures/MaybeExtensionTests.cs @@ -26,7 +26,7 @@ public class MaybeExtensionTests public void MaybeNullableTests() { Assert.IsNull(Maybe.Empty().ToNullable()); - Assert.IsNull(Maybe.Create(0, hasValue: _ => false).ToNullable()); + Assert.IsNull(Maybe.Create(0, evalIsEmpty: () => true).ToNullable()); } [Test] diff --git a/Base/Structures/Maybe.cs b/Base/Structures/Maybe.cs index 315c553..13c88c7 100644 --- a/Base/Structures/Maybe.cs +++ b/Base/Structures/Maybe.cs @@ -4,20 +4,25 @@ using System; public static class Maybe { - public static Maybe Create(T value) => new(value, hasValue: true); - public static Maybe Create(T value, Func hasValue) => new(value, hasValue: hasValue(value)); - public static Maybe Empty() => new(val: default!, hasValue: false); + public static Maybe Create(T value) => new(value); + + public static Maybe Create(T value, Func evalIsEmpty) => + evalIsEmpty() + ? Empty() + : new Maybe(value); + + public static Maybe Empty() => new(); } public readonly record struct Maybe { private readonly T _value; - public readonly bool HasValue; + public bool HasValue { get; } - internal Maybe(T val, bool hasValue) + internal Maybe(T val) : this() { _value = val; - HasValue = hasValue; + HasValue = true; } public T Value @@ -77,7 +82,10 @@ public readonly record struct Maybe ? default : (TOutput)Convert.ChangeType(Value, t); - return Maybe.Create(output, hasValue: _ => output != null)!; + if (output == null) + return Maybe.Empty(); + + return Maybe.Create(output); } catch (InvalidCastException) {