Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 778
user2140261 Avatar asked Mar 27 '13 13:03

user2140261


People also ask

Is string not null or empty?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

How do I check if a string is empty or not?

The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

Is not null or empty string C#?

The IsNullOrEmpty() method returns true if the input is null . IsNullOrEmpty() returns true if the input is an empty string. In C#, this is a zero length string ("").

What does string IsNullOrEmpty return?

The C# IsNullOrEmpty() method is used to check whether the specified string is null or an Empty string. It returns a boolean value either true or false.


3 Answers

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;
like image 52
Anthony Pegram Avatar answered Oct 09 '22 12:10

Anthony Pegram


You could use the ternary operator:

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

FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
like image 36
Jim Mischel Avatar answered Oct 09 '22 13:10

Jim Mischel


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();
like image 10
ssilas777 Avatar answered Oct 09 '22 13:10

ssilas777