Tom Goff's .Net Musings

Tidbits of information regarding .Net, C#, and SQL Server.

String.IsNullOrEmpty Issue & Solution

with 2 comments

I’m sure everyone has heard of the static IsNullOrEmpty[^] method that is available in the String class. Although, you may not have heard about the JIT optimizer bug[^] relating to that method. Essentially, the JIT optimizer is generating “optimized” code that accesses a null variable, thus throwing an exception. You may be tempted to write your own version of this method to get around the bug, like so:

public class StringHelper {
    public static Boolean IsNullOrEmpty(String x) {
        return (null == x || 0 == x.Length);

Unfortunately, the JIT optimizer will generate the same null access exception with this method. There is a solution that relies on the fact[^] that the JIT optimizer (sometimes?) skips try blocks. Meaning it does not apply it’s optimizations to the code inside the try block. If we change our custom version of IsNullOrEmpty as shown below, then it will no longer generate the offending code or the exception.

public class StringHelper {
    public static Boolean IsNullOrEmpty(String x) {
        try {
            return (null == x || 0 == x.Length);
        catch (Exception) {

Although, this may be too much trouble for a method that is suppose to be a convenience. Microsoft has said[^] that this issue is fixed in the next version of Visual Studio.


Written by Tom

September 30, 2007 at 4:58 pm

Posted in .Net, C#, Gotcha, Visual Studio

2 Responses

Subscribe to comments with RSS.

  1. Hi,

    Nice code formatting. How this can be done on wordpress blog. I own one, but I am not able to do so.


    October 3, 2007 at 1:51 am

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: