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
- 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.
Tags: check empty strings, empty strings
Ashish Mohta is A tech blogger who writes about solving day to day problems of people who use computer. He also writes on How to use the applications like Office, PC tips, Online tools,Browsers and more.
All posts by Ashish Mohta | Connect with me @
Twitter |
Linkedin |
Facebook |
Stumble
| Need more help? Ask your Questions at our Support Center














Free Email Subscription


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().