Last active
August 29, 2015 14:01
-
-
Save gowon/8e973727049b1c8ab0ad to your computer and use it in GitHub Desktop.
Simple coalesce extension method for strings. Behaves similarly to the "??" null coalesce operator, but will properly collapse in situations of empty/whitespace strings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class StringCoalesceExtension | |
{ | |
public enum CoalesceProperty | |
{ | |
OnNull = 1, | |
OnNullOrEmpty = 2, | |
OnNullOrWhiteSpace = 4 | |
} | |
public static string Coalesce(this string originalString, params string[] strings) | |
{ | |
return Coalesce(originalString, CoalesceProperty.OnNullOrWhiteSpace, strings); | |
} | |
public static string Coalesce(this string originalString, CoalesceProperty property, params string[] strings) | |
{ | |
if (strings.Length < 1) | |
throw new ArgumentException("Must contain at least one parameter."); | |
var stringArray = new string[strings.Length + 1]; | |
stringArray[0] = originalString; | |
strings.CopyTo(stringArray, 1); | |
foreach (var value in stringArray) | |
{ | |
switch (property) | |
{ | |
case CoalesceProperty.OnNull: | |
if (value == null) continue; | |
break; | |
case CoalesceProperty.OnNullOrEmpty: | |
if (String.IsNullOrEmpty(value)) continue; | |
break; | |
case CoalesceProperty.OnNullOrWhiteSpace: | |
if (String.IsNullOrWhiteSpace(value)) continue; | |
break; | |
} | |
return value; | |
} | |
throw new ConstraintException("All parameters are null or empty. There must be at least one non-empty parameter to coalesce to."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment