From 572c365725eb1b746a30a3447a1e554b418b0372 Mon Sep 17 00:00:00 2001 From: Kyle Ratti Date: Sun, 24 Dec 2023 21:11:25 -0500 Subject: [PATCH] feat: T?.AsMaybe() for reference types --- .../Structures/NullableExtensionTests.cs | 46 ++++++++++++++++++- Base/Structures/NullableExtensions.cs | 3 ++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/Base.Tests/Structures/NullableExtensionTests.cs b/Base.Tests/Structures/NullableExtensionTests.cs index a8875b2..69aee17 100644 --- a/Base.Tests/Structures/NullableExtensionTests.cs +++ b/Base.Tests/Structures/NullableExtensionTests.cs @@ -1,4 +1,5 @@ -using FruityFoundation.Base.Structures; +using System.Linq; +using FruityFoundation.Base.Structures; using NUnit.Framework; namespace Base.Tests.Structures; @@ -12,4 +13,47 @@ public class NullableExtensionTests [Test] public void TestNullableStructOfValueToMaybe() => Assert.AreEqual(Maybe.Just(25), ((int?)25).ToMaybe()); + + [Test] + public void TestNullableReferenceOfNullAsMaybe() + { + string? nullableString = null; + + var result = nullableString.AsMaybe(); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.False); + } + + [Test] + public void TestNullableReferenceOfValueAsMaybe() + { + string? nullableString = "banana"; + + var result = nullableString.AsMaybe(); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo("banana")); + } + + [Test] + public void TestNullableReferenceAsMaybeWorksWithChoose() + { + string?[] stringCollection = + [ + "banana", + "bob", + null + ]; + + var result = stringCollection + .Choose(x => x.AsMaybe()) + .ToArray(); + + Assert.That(result, Is.InstanceOf()); + Assert.That(result, Has.Length.EqualTo(2)); + Assert.That(result[0], Is.EqualTo("banana")); + Assert.That(result[1], Is.EqualTo("bob")); + } } diff --git a/Base/Structures/NullableExtensions.cs b/Base/Structures/NullableExtensions.cs index b1d950b..fe83db8 100644 --- a/Base/Structures/NullableExtensions.cs +++ b/Base/Structures/NullableExtensions.cs @@ -4,4 +4,7 @@ public static class NullableExtensions { public static Maybe ToMaybe(this T? item) where T : struct => item ?? Maybe.Empty(); + + public static Maybe AsMaybe(this T? item) where T : class => + item ?? Maybe.Empty(); }