[c#] One liner for If string is not null or empty else

I usually use something like this for various reasons throughout an application:

if (String.IsNullOrEmpty(strFoo))
{
     FooTextBox.Text = "0";
}
else
{
     FooTextBox.Text = strFoo;
}

If I'm going to be using it a lot I will create a method that returns the desired string. For example:

public string NonBlankValueOf(string strTestString)
{
    if (String.IsNullOrEmpty(strTestString))
        return "0";
    else
        return strTestString;
}

and use it like:

FooTextBox.Text = NonBlankValueOf(strFoo);

I always wondered if there was something that was part of C# that would do this for me. Something that could be called like:

FooTextBox.Text = String.IsNullOrEmpty(strFoo,"0")

the second parameter being the returned value if String.IsNullOrEmpty(strFoo) == true

If not does anyone have any better approaches they use?

This question is related to c# if-statement isnullorempty

The answer is


You could use the ternary operator:

return string.IsNullOrEmpty(strTestString) ? "0" : strTestString

FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;

You can write your own Extension method for type String :-

 public static string NonBlankValueOf(this string source)
 {
    return (string.IsNullOrEmpty(source)) ? "0" : source;
 }

Now you can use it like with any string type

FooTextBox.Text = strFoo.NonBlankValueOf();

Old question, but thought I'd add this to help out,

#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif

This may help:

public string NonBlankValueOf(string strTestString)
{
    return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}

You can achieve this with pattern matching with the switch expression in C#8/9

FooTextBox.Text = strFoo switch
{
    { Length: >0 } s => s, // If the length of the string is greater than 0 
    _ => "0" // Anything else
};