Skip to content

Commit

Permalink
Add Nullable<T>.TryGetValue (resolves #61)
Browse files Browse the repository at this point in the history
  • Loading branch information
oliverbooth committed Feb 26, 2023
1 parent c6849a0 commit d9cf9c8
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -23,6 +23,7 @@
- X10D: Added `IList<T>.Swap(IList<T>)` (#62)
- X10D: Added `IReadOnlyList<T>.IndexOf(T[, int[, int]])`
- X10D: Added `IReadOnlyList<T>.Slice(int[, int]])`
- X10D: Added `Nullable<T>.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()`
Expand Down
24 changes: 24 additions & 0 deletions 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);
}
}
35 changes: 35 additions & 0 deletions X10D/src/Core/NullableExtensions.cs
@@ -0,0 +1,35 @@
namespace X10D.Core;

/// <summary>
/// Extension methods for <see cref="Nullable{T}" />
/// </summary>
public static class NullableExtensions
{
/// <summary>
/// Attempts to get the value of a <see cref="Nullable{T}" />, and returns a value indicating the success of the
/// operation.
/// </summary>
/// <param name="value">The nullable value.</param>
/// <param name="result">
/// When this method returns, contains the result of <see cref="Nullable{T}.Value" />, if
/// <see cref="Nullable{T}.HasValue" /> is <see langword="true" />; otherwise, returns the default value for
/// <typeparamref name="T" />.
/// </param>
/// <typeparam name="T">The type of the value.</typeparam>
/// <returns>
/// <see langword="true" /> if the value's <see cref="Nullable{T}.HasValue" /> is <see langword="true" />; otherwise,
/// <see langword="false" />.
/// </returns>
public static bool TryGetValue<T>(this T? value, out T result)
where T : struct
{
if (value.HasValue)
{
result = value.Value;
return true;
}

result = default;
return false;
}
}

0 comments on commit d9cf9c8

Please sign in to comment.