Skip to content

Commit 76c0e57

Browse files
authored
DefaultIfNullOrWhiteSpace (#10)
1 parent 83f79e2 commit 76c0e57

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using FluentAssertions;
2+
using Xunit;
3+
4+
namespace NetChris.Core.UnitTests;
5+
6+
public class DefaultIfNullOrWhiteSpaceTests
7+
{
8+
[Fact]
9+
public void NullShouldReturnDefault()
10+
{
11+
string? nullString = null;
12+
nullString.DefaultIfNullOrWhiteSpace("default").Should().Be("default");
13+
}
14+
15+
[Fact]
16+
public void EmptyStringShouldReturnDefault()
17+
{
18+
"".DefaultIfNullOrWhiteSpace("default").Should().Be("default");
19+
}
20+
21+
[Fact]
22+
public void WhiteSpaceShouldReturnDefault()
23+
{
24+
" \t\n".DefaultIfNullOrWhiteSpace("default").Should().Be("default");
25+
}
26+
27+
[Fact]
28+
public void NonNullNonWhiteSpaceShouldReturnValue()
29+
{
30+
" Some string \t".DefaultIfNullOrWhiteSpace("default").Should().Be(" Some string \t");
31+
}
32+
}

NetChris.Core/StringExtensions.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,10 @@ public static class StringExtensions
2626

2727
return result;
2828
}
29+
30+
/// <summary>
31+
/// Returns a default value if the string is null or whitespace, otherwise the original string
32+
/// </summary>
33+
public static string DefaultIfNullOrWhiteSpace(this string? value, string defaultValue) =>
34+
string.IsNullOrWhiteSpace(value) ? defaultValue : value!;
2935
}

0 commit comments

Comments
 (0)