Skip to content
8 changes: 8 additions & 0 deletions PowerKit.Tests/FunctionalExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ public void Pipe_Test()
"hello".Pipe(s => s.ToUpper()).Pipe(s => s + "!").Should().Be("HELLO!");
}

[Fact]
public void NullIf_ReferenceType_Test()
{
// Act & assert
"hello".NullIf(v => v == "hello").Should().BeNull();
"world".NullIf(v => v == "hello").Should().Be("world");
Comment thread
Tyrrrz marked this conversation as resolved.
}

[Fact]
public void NullIf_Test()
{
Expand Down
15 changes: 15 additions & 0 deletions PowerKit/Extensions/FunctionalExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,18 @@ internal static class FunctionalExtensions
public string? NullIfWhiteSpace() => !string.IsNullOrWhiteSpace(value) ? value : null;
}
}

// Separate class because C# (CS0111) does not allow two generic methods with identical
// parameter types that differ only by constraint (class vs struct) in the same class.
internal static class ReferenceTypeFunctionalExtensions
{
extension<T>(T value)
where T : class
{
/// <summary>
/// Returns <see langword="null" /> if the value is <see langword="null" /> or matches the specified predicate;
/// otherwise, returns the value.
/// </summary>
public T? NullIf(Func<T, bool> predicate) => value?.Pipe(v => !predicate(v) ? v : null);
}
}