This blog will not only feature tips and hints but also show you the most basic and mundane things. This time I will show you how to check if a string is empty. A very basic task. Nevertheless there are a few ways of doing that. Some good, some even better.
I guess the most natural way to check wether or not a string s; is empty is to do this:
Essentially the same operation comes in quite a few different flavors. You could write this:
All of these examples work but string comparison can be slow and if you want to do it the right way you could use this:
This doesn’t do string comparison and simply checks the length of the string which is relatively fast. Microsofts own FxCop (a code analysis tool) has a performance rule about this:
To test for empty strings, check if String.Length is equal to zero. Constructs such as “”.Equals(someString) and String.Empty.Equals(someString) are less efficient than testing the string length. Replace these with checks for someString.Length == 0.
I would go even further and suggest to use this approach:
As the name suggest this method not only checks if the given string is empty but also checks if it is null. In practise I have rarely encountered a situation where you only want to test if a string is empty and not test if it is null. This also prevents NullReferenceExceptions that could be thrown if you check it using the .Length == 0 approach.
Using Reflector we can see how the IsNullOrEmpty method works:
public static bool IsNullOrEmpty(string value)
if (value != null)
return (value.Length == 0);
If you found this article useful help me out by spreading the word about .NET Toad. You can help by kicking the toad, digg the toad or simply tell your friends.
I looked over the code that you posted from Reflector and it looks like the output for the IsNullOrEmpty method is either incomplete or wrong. Right now from this code it doesn't look like all code paths return a value(i.e. what if a null string is passed based on the code posted?).