views:

288

answers:

6

Which is better to use ?

string myString = "";

String.IsNullOrEmpty(myString);

or

if(myString.Length > 0 || myString != null)

EDIT:

or    if (m.Length > 0 | m != null)**

Former is clearer but is there any performance difference in choosing one of above ?

What if, in case a string is never empty, like if taken from a Text Box, which could be empty but not null ?

Thanks

+4  A: 

Go with string.IsNullOrEmpty(str). It's clearer and more succinct. It will not be a bottle-neck in your application.

If you only need to check for string "emptiness", then I would go with a check against string.Empty since it expresses your intent better.

Skurmedel
Also it's ++ for code reuse
abatishchev
+10  A: 

Well, the version in the question:

if(myString.Length > 0 || myString != null)

would definitely be worse, as you should test for null first (not second) - ideally short-circuiting on null so you don't attempt to call .Length. But generally I'd just use string.IsNullOrEmpty. You could always write an extension method to make it less verbose if you want (you can call extension methods on null values).

static bool HasValue(this string s) {
    return !string.IsNullOrEmpty(s);
}
Marc Gravell
Yeah, nice tip that last one. I am a bit of a sucker for string.Format extension methods :)
Skurmedel
Great one always, never thought about it.
Asad Butt
@Marc Gravell: I realize the method is static, but when calling it on an instance variable not everyone may be able to tell if such call will throw a null reference exception or not.
Esteban Araya
@Esteban - the compiler / runtime can tell, though ;-p
Marc Gravell
I agree with Esteban, the syntax is not 100% clear to the uninitiated. In an attempt to make this clearer, instead of naming the extension method 'HasValue' I would instead name it exactly the same as the static method: 'IsNullOrEmpty', which is allowed: public static bool IsNullOrEmpty(this string s) { return string.IsNullOrEmpty(s); }
Mike Rosenblum
The extension method should start with `if (s == null) throw new NullReferenceException()` (not `ArgumentNullException`). If it looks like an instance method, it behaves like an instance method. If you want it to allow a `null` argument, then call it statically.
280Z28
@Z280Z28: No, that's not right. You should never throw a 'NullReferenceException' in your own code. Extension methods are static methods and therefore should throw an 'ArgumentNullException' (if you are going to throw one -- the examples here should return true or false and not throw). For more on this see: http://stackoverflow.com/questions/463302/argumentnullexception-or-nullreferenceexception-from-extension-method.
Mike Rosenblum
+2  A: 

I'd use the IsNullOrEmpty.

It will be easier to parse when you are looking through the code later on.

Here's another - slightly bizarre - reason. Some later programmer is bound to come along later, scratch his beard and say "I think that myString.trim().Length != 0 is better" and change it.

As others have pointed out: checking for null second is a potential null access error waiting to happen - the library routine is guaranteed to be ok.

Fortyrunner
Hence the creation of `IsNullOrWhitespace`: http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace(VS.100).aspx
280Z28
+1  A: 

The String.IsNullOrEmpty is the better choise if you are unsecure about how to test the different states of the string reference (which you obviously are, as you got it wrong... ;).

Using the IsNullOrEmpty method:

if (String.IsNullOrEmpty(s)) ...

is equivalent to using a short circuit test for null and zero length:

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

If you know that the referene can't be null, you can skip that check and just check the length:

if (s.Length == 0) ...

The IsNullOrEmpty method would also work for normal situations, but in the case where something went wrong and the reference is actually null, the IsNullOrEmpty method would silently accept it, while you would normally want to be made aware of the error.

Guffa
A: 

I believe the String.IsNullOrEmpty(String s) is implemented as:

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

in the API.

Bobby
... which means as far as IL code goes, the same IL is generated. Neither is faster than the other.
Bobby
I am not sure if this ok to put it here, but using Disassembler, this is what is in the API for String.IsNullOrEmptr(value) { if (value != null) { return (value.Length == 0); } return true;}
Asad Butt
That's probably an artefact of disassembling rather than how the code actually looks.
ICR
+1  A: 

As others have said, IsNullOrEmpty() is superior to the manual checks for purposes of maintainability and isn't likely to suffer in performance thanks to the JIT compiler's runtime decisions about inlining (see Eric Gunnerson's comments).

In case anyone else is wondering what the actual .NET implementation looks like, here is the .NET 4 code:

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool IsNullOrEmpty(string value)
{
    if (value != null)
    {
        return (value.Length == 0);
    }
    return true;
}

That attribute indicates the method will also be inlined in NGen (that is, native) images.

ladenedge