Strings and IsNullOrEmpty

href="">Jesse aks:

>Tired of doing this: "if(s == null || s ==

Yea, we have heard that request before... here is a method we are looking at
adding a the Whidbey release of the .NET Framework on the System.String

static color=#0000ff size=2>bool IsNullOrEmpty( color=#0000ff size=2>string str)

what do you think?

Comments (8)

  1. Miguel de Icaza says:

    The method might seem convenient, but most of the time I have found that this situation arises from trying to cover up deeper bugs.

    Your code should stick to a particular protocol on the use of strings, and you should understand the use of the protocol in library code and in the code you are working with.

    The NullOrEmpty protocol is typically a quick fix (so the real problem is still somewhere else, and you got two protocols in use) or it is a lack of expertise in a particular protocol when implementing new code (and again, you should really know what your return values are).


  2. How about changing String.Equals() to throw ArgumentNullException if the argument is null? That should satisfy Miguel’s complaint about hiding bugs and allow Jesse to write String.Empty.Equals(x) (or "".Equals(x))

  3. Sherrod Segraves says:

    "IsNullOrEmpty" is kind of lengthy. What about naming it "HasData"?

    In either case, I don’t think the proposal is useful enough to offset the clutter of an additional method.

  4. I personally like it. I think it’s readable and with intellisense length is not as important to me as readability.

  5. I agree entirely with Samer here … There are much, much longer properties and what not in the framework – with intellisense, it doesn’t really matter.


  6. adam ac says:

    What about using :

    if ("".equals(NullString)) {

  7. I agree with Miguel. Any convenience here is outweighed by the fact that it will be misused by inexperienced ASP.Net developers everywhere. Chances are, you are going to have to deal with the difference between Null and Empty at some point, especially if you are persisting to a RDBMS. The .Net framework is big enough already. Adding convenience methods like this to core types wouldn’t be my first choice.

    My two cents… Brent

  8. David says:

    I find myself using a variant of this:

    if (s == null || s.Trim() == String.Empty())

    when validating and storing strings that can originate in a UI. In the UI it won’t be null (since it’s probably aTextBox), but the validation lives in an object property and has to cope with any source.

    I would tend to agree with Brent, though. The framework is big enough without either of these.

Skip to main content