1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-10 02:45:41 +00:00

Add string.With*Alternative

Serves as a way to specify a custom alternative in cases where AsNullIf* does not satisfy
This commit is contained in:
Oliver Booth 2022-03-06 17:31:22 +00:00
parent c151a9c754
commit 45804c2da6
No known key found for this signature in database
GPG Key ID: 32A00B35503AF634

View File

@ -498,4 +498,45 @@ public static class StringExtensions
return (includeWhiteSpace ? value?.AsNullIfWhiteSpace() : value?.AsNullIfEmpty()) ?? alternative;
}
/// <summary>
/// Normalizes a string which may be either <see langword="null" /> or empty to a specified alternative.
/// </summary>
/// <param name="value">The value to normalize.</param>
/// <param name="alternative">The alternative string.</param>
/// <returns>
/// <paramref name="alternative" /> if <paramref name="value" /> is <see langword="null" /> or empty; otherwise,
/// <paramref name="value" />.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="alternative" /> is <see langword="null" />.</exception>
public static string WithEmptyAlternative(this string? value, string alternative)
{
if (alternative is null)
{
throw new ArgumentNullException(nameof(alternative));
}
return string.IsNullOrEmpty(value) ? alternative : value;
}
/// <summary>
/// Normalizes a string which may be either <see langword="null" />, empty, or consisting of only whitespace, to a
/// specified alternative.
/// </summary>
/// <param name="value">The value to normalize.</param>
/// <param name="alternative">The alternative string.</param>
/// <returns>
/// <paramref name="alternative" /> if <paramref name="value" /> is <see langword="null" />, empty, or consists of only
/// whitespace; otherwise, <paramref name="value" />.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="alternative" /> is <see langword="null" />.</exception>
public static string WithWhiteSpaceAlternative(this string? value, string alternative)
{
if (alternative is null)
{
throw new ArgumentNullException(nameof(alternative));
}
return string.IsNullOrWhiteSpace(value) ? alternative : value;
}
}