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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What's wrong with string concatenation? Is it really that bad?
@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.
I think I got your point here. But in some cases, we also need to actually process the Trimmed string (and turn them into empty string if it's null). Is concatenation to avoid null still a bad idea for that case?
Forget my previous comment, I've found the answer here : stackoverflow.com/questions/416473/…
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.

Comments

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.

2 Comments

Yes, actually some of our implementation does using the helper / extension method (and some other directly using the code like the sample above :().
@andri It's never late and always worth refactoring. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.