Extension Method: Return another string if string is null or empty

Just a tiny little extension method. You may know the ?? operator for null checks:

var something = objectThatCouldBeNull ?? anotherObject;

Basically if objectThatCouldBeNull is null, then anotherObject is used instead. Unfortunately, this does not work with empty strings, so here is a quick extension method for that:

public static string IfEmpty(this string input, string otherString)
{
    if (string.IsNullOrEmpty(input)) return otherString;
    return input;
}

call it like

var myString = someString.IfEmpty("someOtherString");

The nice thing on extension methods is that you can call them on null instances of an object, so a call to

((string)null).IfEmpty("SomethingElse");

is safe.

Comments (2)

John SheehanJanuary 16th, 2010 at 00:38

I think I have the same thing but I named it the same as the Nullable.GetValueOrDefault(value) method. Longer than IfEmpty but I like the consistency.

mstumJanuary 16th, 2010 at 02:22

I think I have 5 or so for various classes 🙂 All those TryParse methods make the code too long, especially when there is casting involved. I was unsure about the name IfEmpty, but I just say "It's a fluid interface!" 😉