Skip to content

Commit

Permalink
Adding ToNullable() to unsafe namespace (fixing #18)
Browse files Browse the repository at this point in the history
  • Loading branch information
nlkl committed Aug 17, 2017
1 parent 6dda99e commit 56396bf
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Optional.Tests/UnsafeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ namespace Optional.Tests
[TestClass]
public class UnsafeTests
{
[TestMethod]
public void Maybe_ToNullable()
{
Assert.AreEqual(default(int?), Option.None<int>().ToNullable());
Assert.AreEqual(1, Option.Some(1).ToNullable());
}

[TestMethod]
public void Maybe_GetValueOrDefault()
{
Expand Down Expand Up @@ -59,6 +66,13 @@ public void Maybe_GetUnsafeValue()
}
}

[TestMethod]
public void Either_ToNullable()
{
Assert.AreEqual(default(int?), Option.None<int, bool>(false).ToNullable());
Assert.AreEqual(1, Option.Some<int, bool>(1).ToNullable());
}

[TestMethod]
public void Either_GetValueOrDefault()
{
Expand Down
30 changes: 30 additions & 0 deletions src/Optional/Unsafe/OptionUnsafeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ namespace Optional.Unsafe
{
public static class OptionUnsafeExtensions
{
/// <summary>
/// Converts an optional to a Nullable&lt;T&gt;.
/// </summary>
/// <param name="option">The specified optional.</param>
/// <returns>The Nullable&lt;T&gt; instance.</returns>
public static T? ToNullable<T>(this Option<T> option) where T : struct
{
if (option.HasValue)
{
return option.Value;
}

return default(T?);
}

/// <summary>
/// Returns the existing value if present, otherwise default(T).
/// </summary>
Expand Down Expand Up @@ -35,6 +50,21 @@ public static T ValueOrFailure<T>(this Option<T> option)
throw new OptionValueMissingException();
}

/// <summary>
/// Converts an optional to a Nullable&lt;T&gt;.
/// </summary>
/// <param name="option">The specified optional.</param>
/// <returns>The Nullable&lt;T&gt; instance.</returns>
public static T? ToNullable<T, TException>(this Option<T, TException> option) where T : struct
{
if (option.HasValue)
{
return option.Value;
}

return default(T?);
}

/// <summary>
/// Returns the existing value if present, otherwise default(T).
/// </summary>
Expand Down

0 comments on commit 56396bf

Please sign in to comment.