andri
andri

Reputation: 1021

Handling null / empty string

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?

Upvotes: 0

Views: 331

Answers (3)

Kirin Yao
Kirin Yao

Reputation: 1636

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499810

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.

Upvotes: 4

Lemur
Lemur

Reputation: 2665

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.

Upvotes: 2

Related Questions