ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

DefaultIfEmpty

returns default value if string is null or empty or white spaces string

Source

public static string DefaultIfEmpty(this string str, string defaultValue, bool considerWhiteSpaceIsEmpty = false)
{
    return (considerWhiteSpaceIsEmpty ? string.IsNullOrWhiteSpace(str) : string.IsNullOrEmpty(str)) ? defaultValue : str;
}

Example

string str = null;
str.DefaultIfEmpty("I'm nil") // return "I'm nil"

string str1 = string.Empty;
str1.DefaultIfEmpty("I'm Empty") // return "I'm Empty!"

string str1 = "     ";
str1.DefaultIfEmpty("I'm WhiteSpaces strnig!", true) // return "I'm WhiteSpaces strnig!"

Author: Alexander Gubenko

Submitted on: 22 apr. 2011

Language: C#

Type: System.String

Views: 9918