0

Before .NET 4 is out, we've been doing something like this to check for null / empty string :

String s;
if ((s + "").Trim().Length == 0)
{
    //do something
}

While the above method works pretty well for us, I know that in .NET 4, we got a IsNullOrWhiteSpace method to do the similar thing.

My question is, which one is better? Do we should switch to use the built-in function instead?

andri
  • 1,021
  • 1
  • 9
  • 16

3 Answers3

4

On .NET 4, I'd definitely use the built in method. After all, it says exactly what you're trying to do.

If you're stuck before .NET 4, why not use:

if (s == null || s.Trim() == "")

Or

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

? Both of those say what you want to achieve.

I definitely wouldn't use string concatenation here. Performance aside, you're not interested in string concatenation. Whenever you find your code doing something which really isn't part of what you're trying to achieve, you should try to improve it for the sake of readability.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • What's wrong with string concatenation? Is it really that bad? – andri Mar 17 '13 at 17:36
  • 1
    @andri: It's fine when you *want* to concatenate strings. But you don't. You're *only* using concatenation to avoid handling null references. That's not good. – Jon Skeet Mar 17 '13 at 18:06
  • I think I got your point here. But in some cases, we also need to actually process the `Trim`med string (and turn them into empty string if it's `null`). Is concatenation to avoid `null` still a bad idea for that case? – andri Mar 18 '13 at 02:23
  • Forget my previous comment, I've found the answer here : http://stackoverflow.com/questions/416473/coalesce-vs-empty-string-concatenation – andri Mar 18 '13 at 03:23
2

I personally use IsNullOrWhiteSpace, mostly because using it makes code clearer to read and it handles more cases (the WhiteSpace part). It depends on your preferences, because both methods does pretty the same thing.

Lemur
  • 2,659
  • 4
  • 26
  • 41
2

Why not write a helper method to implement what IsNullOrWhiteSpace does before .NET 4? Just like

public static boolean IsNullOrWhiteSpace(string input)
{
    return string.IsNullOrEmpty(input) || input.Trim() == string.Empty;
}

Don't use concatenation here as Jon said. It's not a good practice for checking null/empty.

Kirin Yao
  • 1,606
  • 2
  • 14
  • 21
  • Yes, actually *some* of our implementation does using the helper / extension method (and some other directly using the code like the sample above `:(`). – andri Mar 18 '13 at 02:17
  • @andri It's never late and always worth refactoring. :) – Kirin Yao Mar 18 '13 at 03:00