5 Wrong ways to check empty strings

It is one of the common mistake that people compare a string with “” or String.Empty in VB.Net or C# to find its empty. Here are few examples.

// C# Wrong Ways

  1. if ( s == “” )
  2. if ( s == string.Empty )
  3. if ( s.Equals(””) )
  4. if ( s.Equals ( String.Empty)
  5. if ( string.Equals(s,””)
  6. if ( string.Equals ( s,String.Empty ))

So what’s the correct way to do it ? Check for length too.

// [ C# ] Correct Way

if ( s.Length == 0 )

This is in continuation of our last post on Check for length too when you check for null strings in VB.Net and C#

Read below for the right approach.

  • Ryan Heaney, March 27, 2008:

    I agree with Shahar. string.IsNullOrEmpty is the best, managed way to test. It’s static and guaranteed not to throw a NullReferenceException. You can’t say that about .Length.

    If you look at the disassembly of string.IsNullOrEmpty you will see what it does.
    .method public hidebysig static bool IsNullOrEmpty(string ‘value’) cil managed
    {
    .maxstack 8
    L_0000: ldarg.0
    L_0001: brfalse.s L_000d
    L_0003: ldarg.0
    L_0004: callvirt instance int32 System.String::get_Length()
    L_0009: ldc.i4.0
    L_000a: ceq
    L_000c: ret
    L_000d: ldc.i4.1
    L_000e: ret
    }

    This translates to (C#):
    public static bool IsNullOrEmpty(string value)
    {
    if (value != null)
    {
    return (value.Length == 0);
    }
    return true;
    }

    Now while you can perform this operation on your own, the whole point of the .NET Framework is the fact that this is managed code. If for some reason Microsoft decides to change the implementation of the string class such that there is another case in which it is empty, it would change its implementation here. And you would never have to worry about your code breaking due to an underlying change.

    So, in short, use string.IsNullOrEmpty().

LEAVE A REPLY

Please enter your comment!
Please enter your name here