Dim
Dim

Reputation: 453

If string isnull or Empty return string

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?

Upvotes: 2

Views: 812

Answers (2)

Klaus Gütter
Klaus Gütter

Reputation: 11977

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;

Upvotes: 6

Patrick Hofman
Patrick Hofman

Reputation: 156948

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

Upvotes: 3

Related Questions