fix: handle nullable value types in Maybe.Cast

This commit is contained in:
Kyle Ratti 2024-02-07 20:57:33 -05:00
parent d69441984f
commit a56a4ff5f2
No known key found for this signature in database
GPG Key ID: 4D429B6287C68DD9
2 changed files with 66 additions and 1 deletions

View File

@ -90,4 +90,62 @@ public class MaybeTests
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo(30));
}
[Test]
public void Cast_ToNullableReferenceType_ReturnsEmptyMaybe_WhenHasNoValue()
{
// Arrange
var maybe = Maybe.Empty<string>();
// Act
var result = maybe.Cast<string?>();
// Assert
Assert.That(result, Is.InstanceOf<Maybe<string?>>());
Assert.That(result.HasValue, Is.False);
}
[Test]
public void Cast_ToNullableReferenceType_ReturnsMaybe_WhenHasValue()
{
// Arrange
var maybe = Maybe.Just("banana");
// Act
var result = maybe.Cast<string?>();
// Assert
Assert.That(result, Is.InstanceOf<Maybe<string?>>());
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo("banana"));
}
[Test]
public void Cast_ToNullableValueType_ReturnsEmptyMaybe_WhenHasNoValue()
{
// Arrange
var maybe = Maybe.Empty<int>();
// Act
var result = maybe.Cast<string?>();
// Assert
Assert.That(result, Is.InstanceOf<Maybe<string?>>());
Assert.That(result.HasValue, Is.False);
}
[Test]
public void Cast_ToNullableValueType_ReturnsMaybe_WhenHasValue()
{
// Arrange
var maybe = Maybe.Just(25);
// Act
var result = maybe.Cast<int?>();
// Assert
Assert.That(result, Is.InstanceOf<Maybe<int?>>());
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo(25));
}
}

View File

@ -70,7 +70,14 @@ public readonly struct Maybe<T>
try
{
return (TOutput)Convert.ChangeType(Value, typeof(TOutput))!;
var t = typeof(TOutput);
t = Nullable.GetUnderlyingType(t) ?? t;
var output = Value == null
? default
: (TOutput)Convert.ChangeType(Value, t);
return Maybe.Just(output, hasValue: _ => output != null)!;
}
catch (InvalidCastException)
{