String silliness

Yesterday at work, Carlos and I had a silly converstation about the best way to check if a trimmed string is NULL or EMPTY.

I usually do this:

if (string.IsNullOrEmpty(x) x.Trim().Length == 0)

Carlos liked this better because its prettier:

if (x == null || x.Trim().Length == 0)

Of course, I took offense to that because I find my version to be quite attractive as well. So, instead of settling on which one is prettier, we broke it down into basic operations to see which one would be (theoretically) quicker.

In most cases, x will be a valid string.

string x = “123”;
if (string.IsNullOrEmpty(x) || x.Trim().Length == 0)

1 – Check for null
2 – Check for empty (.Length == 0)
3 – Trim the string
4 – Check the length
Under normal circumstances, there are 4 things to do

string x = “123”;
if (x == null || x.Trim().Length == 0)

1 – Check for null
2 – Trim
3 – Check the length
Under normal circumstances, there are 3 things to do.

So, the second choice is the better one, and we will use that going forward.

Out of curiosity, I took a look at the string source code to see how it was doing some things.

if (x.Trim().Length == 0)
or
if (x.Trim() == string.Empty)

.Length has been my means of choice. Its just a property value as opposed to a comparison. The string source code does it the same way.

System.String.IsNullOrEmpty()
if (value != null) { return value.Length == 0;} return true;

I think we’ve made a lot of progress towards solving some insignificant problems. Super.

Advertisements

4 Responses to String silliness

  1. Mike says:

    So silly question, why dont you use string.isnullorempty in the first place?

  2. Mike says:

    So silly question, why dont you use string.isnullorempty in the first place?

  3. Jay says:

    Didn’t see this comment… i added a related comment to the other post.

    Anyway:

    string x = null;
    string.IsNullOrEmpty(x.Trim());

    Boom! You can’t call methods on a null.

  4. Jay says:

    Didn’t see this comment… i added a related comment to the other post.

    Anyway:

    string x = null;
    string.IsNullOrEmpty(x.Trim());

    Boom! You can’t call methods on a null.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: