diff --git a/CHANGELOG.md b/CHANGELOG.md index e43fa9241..93cf30f2c 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 000000000..eda68835e --- /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 000000000..4c066e901 --- /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; + } +}