From 5123d7f46328ca35b7353257783124c5fb9ce0eb Mon Sep 17 00:00:00 2001 From: matthew Date: Wed, 22 Oct 2025 14:29:58 +0100 Subject: [PATCH] Added TryGetNonNull extension method, and tests, and bumped version to 12.2.0 --- Directory.Build.props | 6 ++-- .../ObjectExtensionTests.cs | 28 +++++++++++++++++++ OnixLabs.Core/Extensions.Object.cs | 20 +++++++++++++ 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 5e4e445..93e6cb0 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,9 +2,9 @@ - 12.1.1 - 12.1.1 - 12.1.1 + 12.2.0 + 12.2.0 + 12.2.0 net8.0;net9.0 13 enable diff --git a/OnixLabs.Core.UnitTests/ObjectExtensionTests.cs b/OnixLabs.Core.UnitTests/ObjectExtensionTests.cs index c699ad2..a00b188 100644 --- a/OnixLabs.Core.UnitTests/ObjectExtensionTests.cs +++ b/OnixLabs.Core.UnitTests/ObjectExtensionTests.cs @@ -360,4 +360,32 @@ public async Task ToSuccessAsyncShouldProduceTheExpectedResult() Success success = Assert.IsType>(result); Assert.Equal(expected, success.Value); } + + [Fact(DisplayName = "TryGetNonNull should produce the expected result (true)")] + public void TryGetNotNullShouldProduceExpectedResultTrue() + { + // Given + const string? value = "Hello, World!"; + + // When + bool result = value.TryGetNonNull(out string output); + + // Then + Assert.True(result); + Assert.NotNull(output); + } + + [Fact(DisplayName = "TryGetNonNull should produce the expected result (false)")] + public void TryGetNotNullShouldProduceExpectedResultFalse() + { + // Given + const string? value = null; + + // When + bool result = value.TryGetNonNull(out string? output); + + // Then + Assert.False(result); + Assert.Null(output); + } } diff --git a/OnixLabs.Core/Extensions.Object.cs b/OnixLabs.Core/Extensions.Object.cs index 37a9145..4b33e1b 100644 --- a/OnixLabs.Core/Extensions.Object.cs +++ b/OnixLabs.Core/Extensions.Object.cs @@ -16,6 +16,7 @@ using System.Collections; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Text; using System.Threading; @@ -226,4 +227,23 @@ public static async Task> ToOptionalAsync(this Task value, Ca /// Returns a representation of the current . public static async Task> ToSuccessAsync(this Task value, CancellationToken token = default) => Result.Success(await value.WaitAsync(token).ConfigureAwait(false)); + + /// + /// Attempts to extract a non-null value from the current nullable . + /// + /// The current nullable to test for nullability. + /// The non-null value when this method returns ; otherwise, . + /// The underlying type of the value. + /// Returns if the current nullable is not null; otherwise, . + public static bool TryGetNonNull(this T? value, [NotNullWhen(true)] out T result) + { + if (value is null) + { + result = default!; + return false; + } + + result = value; + return true; + } }