Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.IsNullOrEmpty using Trim()

I want to remove the first line:

                 !string.IsNullOrEmpty(cell.Text) 

will this cause any issue?

I ran across this in some code:

                if ((id % 2 == 0)
                    && !string.IsNullOrEmpty(cell.Text)
                    && !string.IsNullOrEmpty(cell.Text.Trim())
                    )

I think the first string.IsNullOrEmpty would return false on a string with spaces
and the line with Trim() takes care of that, so the first IsNullOrEmpty is useless

But before I remove the line without the trim I thought I'd run it by the group.

like image 363
Brad Boyce Avatar asked Mar 14 '12 17:03

Brad Boyce


2 Answers

if cell.Text is null, you'd have an exception without that first check.

like image 84
jcomeau_ictx Avatar answered Oct 05 '22 10:10

jcomeau_ictx


In .NET 4.0:

if (id % 2 == 0 && !string.IsNullOrWhiteSpace(cell.Text))
{
    ...
}

In older versions you should keep the two tests because if you remove the first and cell.Text is null, you will get a NRE on the second when you try to invoke .Trim on a null instance.

Or you could also do this:

if (id % 2 == 0 && string.IsNullOrWhiteSpace((cell.Text ?? string.Empty).Trim()))
{
    ...
}

or even better, you could write an extension method for the string type that will do this so that you could simply:

if (id % 2 == 0 && !cell.Text.IsNullOrWhiteSpace())
{
    ...
}

which might look like this:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        return string.IsNullOrEmpty((value ?? string.Empty).Trim());
    }
}
like image 26
Darin Dimitrov Avatar answered Oct 05 '22 09:10

Darin Dimitrov