If string isnull or Empty return string

Viewed 487

I know how to check when a string is NullOrWhiteSpace. But i want to make my code shorter. And to return a value if my string is null or empty.

Till now i use this:

string Foo=textbox1.Text;
if(string.IsNullOrWhiteSpace(textbox1.Text);
  textbox1.Text="UserName";

Is this possible to return this result using one line of code?

string Foo=textbox1.Text ?? "UserName";

In this example it returns me ""; So it thinks that my textbox it is not null, and it doesnt returns me the result i want. Is there any working example for my case?

2 Answers

textbox1.Text will never be null. If the textbox is empty, it is "", not null. You might use

string Foo = string.IsNullOrWhiteSpace(textbox1.Text) ? "UserName": textbox1.Text;

The null coalescing operator just works with null. Not an empty string.

You could write an extension method to do what you want though.

public static class EX
{
    public static string IfNullOrWhiteSpace(this string s, string replacement)
    {
        if (string.IsNullOrWhiteSpace(s))
        {
            return replacement;
        }

        return s;
    }
}

Use it like this:

string Foo = textbox1.Text.IfNullOrWhiteSpace("UserName");
Related