String.IsNullOrEmpty is great, right?

Do you know of String.IsNullOrEmpty and do you use it? You do? Think again after reading this blog post. Ooops, it might not work and even worse, it might not work only in release (optimized) configuration. Apparently JIT optimizer is to blame. What a nightmare for a developer - the same program might not work deployed at client and worse, the bug is not easy to catch either.

But now, here comes the cherry on the cake. MS recognizes this bug and they will fixes it soon, post Orcas. Note that Orcas is targeted for late 2007 or something.

I guess I'll have to replace all my String.IsNullOrEmpty calls with text == null || text == string.Empty.

Comments (8) -

  • Mlad

    6/22/2006 6:39:21 PM | Reply

    everything is solved with

    string s = string.Empty;
    if (s.Length == 0)

    always declare your string as string.empty and check for length...

    Null strings should be in the code if you ask me anyways...

  • Miha Markic

    6/22/2006 11:28:26 PM | Reply

    Hi,

    You did mean "Null strings should *not* be in the code if you ask me anyways..."
    Why not? Null has a special meaning - it means that the string isn't set. That's why MS introduced nullable types, too.
    And your solution makes potentially unnecessary assignments Smile

  • Hugo

    6/23/2006 9:58:14 AM | Reply

    I've tested the code. When you do something in the then-part like:
       Console.WriteLine("x is null or empty");
    then everything seems to be OK.
    So, it obviously has something to do with optimization.

  • Mladen

    6/23/2006 2:45:50 PM | Reply

    yeah i meant it "not in the code"

    well i hate nulls Smile)
    i think that they shouldn't exist at all Smile)
    It's just more work to handle them....
    but i also know that they are necesary.

    I tend to always declare strings a string.Empty at the begining.
    gives me less grief in future development.

  • Miha Markic

    6/23/2006 5:34:18 PM | Reply

    Mladen,

    Of course, as long as you have a consistent strategy its fine. And apparently your way is good, since you won't encounter the bug in question Smile

  • Miha Markic

    6/23/2006 5:35:34 PM | Reply

    Hugo,

    Yup, seems so, even MS admits it. However, they didn't say what exactly is going on and how serious it is.

  • Andrej Tozon

    6/26/2006 10:16:52 PM | Reply

    I like nullable strings. Well, used to like them anyway... Smile

    It's always good to set the string to its initial value, because most of the time you know how you're going to build it and/or what value it is supposed to hold, when the procedure returns. However, if string is an input parameter to your proc, then you don't have much choice... I'd prefer "text == null || text.Length == 0" over "text == null || text == string.Empty" though... But I'm nitpicking now...

  • Miha Markic

    8/14/2006 12:37:40 PM | Reply

    Note: The last comment was accidently lost. Sorry.

Loading