DANGER ! String.IsNullOrEmpty can lead to runtime Null exceptions !!
Posted
Tue, Apr 4 2006 3:40
by
bill
UPDATE: This bug was fixed in .NET 2.0 SP1
940900 (http://support.microsoft.com/kb/940900/ ) FIX: You receive the NullReferenceException exception when you call the String.IsNullOrEmpty function in an application that is built on the .NET Framework 2.0
I saw a little talk in the blogshpere about using String.IsNullOrEmpty in .NET 2.0, so I thought, just for fun I would run it through a series of tests. Unfortunately in doing so I found a very serious bug with it. The following C# code shows the problem:
classProgram
{
static void Main(string[] args)
{
Console.WriteLine("starting");
test(null);
Console.WriteLine("finished");
Console.ReadLine();
}
static void test(string x)
{
for (int j = 0; j < 10; j++)
{
if (String.IsNullOrEmpty(x))
{
//TODO:
}
}
}
}
Have you spotted the problem ? The astute of you are probably saying "yeh it's in that lame language C#", and although you'd be right, that's not the actual gotchya here.
The problem is when you compile this application as a release build with optimizations on and run it from outside of the IDE. Note from inside the IDE all seems fine. but when run form outside this will lead to a null exception being thrown at runtime. Try it for yourselves !
Now in all fairness, this is actually a JIT optimization problem that impacts both VB and C#. Vb.NET does provide a pretty good alternative syntax that does not have this issue, via the:
If x = Nothing syntax.
Of course in both VB and C# you could use the:
If x Is Nothing OrElse x.Length= 0 Then
approach, but that seems to loose a bit in the readability.
So String.IsNullOrEmpty can cause unexpected runtime errors that you won't detect when running from inside the IDE. I recommend using extreme CAUTION when using this method.