From d9cf9c8db5cf7453191c7a1356584d2802e80604 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 26 Feb 2023 00:35:22 +0000 Subject: [PATCH] Add Nullable.TryGetValue (resolves #61) --- CHANGELOG.md | 1 + X10D.Tests/src/Core/NullableTests.cs | 24 +++++++++++++++++++ X10D/src/Core/NullableExtensions.cs | 35 ++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 X10D.Tests/src/Core/NullableTests.cs create mode 100644 X10D/src/Core/NullableExtensions.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index e43fa92..93cf30f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ - X10D: Added `IList.Swap(IList)` (#62) - X10D: Added `IReadOnlyList.IndexOf(T[, int[, int]])` - X10D: Added `IReadOnlyList.Slice(int[, int]])` +- X10D: Added `Nullable.TryGetValue(out T)` (#61) - X10D: Added `Point.IsOnLine(LineF)`, `Point.IsOnLine(PointF, PointF)`, and `Point.IsOnLine(Vector2, Vector2)` - X10D: Added `PointF.IsOnLine(LineF)`, `PointF.IsOnLine(PointF, PointF)`, and `PointF.IsOnLine(Vector2, Vector2)` - X10D: Added `Point.ToSize()` diff --git a/X10D.Tests/src/Core/NullableTests.cs b/X10D.Tests/src/Core/NullableTests.cs new file mode 100644 index 0000000..eda6883 --- /dev/null +++ b/X10D.Tests/src/Core/NullableTests.cs @@ -0,0 +1,24 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using X10D.Core; + +namespace X10D.Tests.Core; + +[TestClass] +public class NullableTests +{ + [TestMethod] + public void TryGetValue_ShouldBeTrue_GivenValue() + { + int? value = 42; + Assert.IsTrue(value.TryGetValue(out int returnedValue)); + Assert.AreEqual(value, returnedValue); + } + + [TestMethod] + public void TryGetValue_ShouldBeFalse_GivenNull() + { + int? value = null; + Assert.IsFalse(value.TryGetValue(out int returnedValue)); + Assert.AreEqual(default, returnedValue); + } +} diff --git a/X10D/src/Core/NullableExtensions.cs b/X10D/src/Core/NullableExtensions.cs new file mode 100644 index 0000000..4c066e9 --- /dev/null +++ b/X10D/src/Core/NullableExtensions.cs @@ -0,0 +1,35 @@ +namespace X10D.Core; + +/// +/// Extension methods for +/// +public static class NullableExtensions +{ + /// + /// Attempts to get the value of a , and returns a value indicating the success of the + /// operation. + /// + /// The nullable value. + /// + /// When this method returns, contains the result of , if + /// is ; otherwise, returns the default value for + /// . + /// + /// The type of the value. + /// + /// if the value's is ; otherwise, + /// . + /// + public static bool TryGetValue(this T? value, out T result) + where T : struct + { + if (value.HasValue) + { + result = value.Value; + return true; + } + + result = default; + return false; + } +}