One liner for If string is not null or empty else

182,062

Solution 1

There is a null coalescing operator (??), but it would not handle empty strings.

If you were only interested in dealing with null strings, you would use it like

string output = somePossiblyNullString ?? "0";

For your need specifically, there is the conditional operator bool expr ? true_value : false_value that you can use to simplify if/else statement blocks that set or return a value.

string output = string.IsNullOrEmpty(someString) ? "0" : someString;

Solution 2

You could use the ternary operator:

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

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

Solution 3

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();

Solution 4

This may help:

public string NonBlankValueOf(string strTestString)
{
    return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}
Share:
182,062
user2140261
Author by

user2140261

I Need a Job.

Updated on November 13, 2020

Comments

  • user2140261
    user2140261 over 3 years

    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?

  • Devin Burke
    Devin Burke over 11 years
    +1 for a good example of when to use null coalesc, although the OP may need it to catch empty string in his/her case.
  • SearchForKnowledge
    SearchForKnowledge over 9 years
    Thanks for the function :)
  • mochsner
    mochsner about 3 years
    Is there a way to do this 2nd thing (string output = string.IsNullOrEmpty(someString) ? "0" : someString;), but if 'someString' is an expression, then capture the result of that expression and return it in the end? I haven't found anything on this yet, but find it would be very useful.