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
- if ( s == “” )
- if ( s == string.Empty )
- if ( s.Equals(””) )
- if ( s.Equals ( String.Empty)
- if ( string.Equals(s,””)
- 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.
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
L_0001: brfalse.s L_000d
L_0004: callvirt instance int32 System.String::get_Length()
This translates to (C#):
public static bool IsNullOrEmpty(string value)
if (value != null)
return (value.Length == 0);
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().