Not Rocket Science » Extension Method: Return another string if string is null or empty (original) (raw)

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.

January 16th, 2010 inDevelopment