While working in the forums a user reported that the use of String.IsNullOrEmpty could cause your code to generate an exception due to its use in certain circumstances and should not be used! 
 
Is that true? Well yes but no…and that no is a real qualified No. Let me explain why you should not even be concerned about this and continue using IsNullOrEmpty without any concerns. The issue was reported in this connect issue entitled Null Exemption caused by JIt optimisation around String.IsNullOrEmpty. Don’t read it yet, let me save you some time reading it.
 
The user stated that he had discovered that if you placed String.IsNullOrEmpty in a tight loop, and I mean tight, then compiled it for release with optimizations it would generate an exception; a System.NullReferenceException. Here is an example. Note I simplified the user’s example of the code which will do it:
 
string Fail = null;
 
for (int index = 0; index < 10; index++)
    if (string.IsNullOrEmpty(Fail))
    { 
        // Yes leave this empty
    } 

Yes it fails, and Microsoft, even though it was reported in 06, said they would fix it until what is now .Net 3.5.

People are up in arms on this issue….

But wait. There is a simple fix and the fix is not a fix because the code above is atypical in how someone actually programs and no real fix is required!

Here is how one can fix it:

string Fail = null;
 
for (int index = 0; index < 10; index++)
    if (string.IsNullOrEmpty(Fail))
        Console.Write(index);

In other words, don’t program empty constructs and you won’t have any problems! By simply doing work within the loop and not having an empty construct fixes the non problem.

People are up in arms that this should be fixed immediately! The nay-saying neighbobs of negativism are saying that a patch should be immediately done! Why hasn’t Microsoft fixed this. Some are suggesting that code out in the field at client sites are prone to failure and clients will be lost.

Oh, please…to reference a Forest Gump quote, “Programming is as Programming does”. If one is creating empty constructs and leaving it in code, that’s analogous to the person walking along the train tracks listening to music…who’s fault is it that they did not hear the train….hmmmm?

Share