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:
if (s==“”)
//empty
Essentially the same operation comes in quite a few different flavors. You could write this:
if (Equals(s,“”))
//empty
or this:
if (String.Empty.Equals(s))
//empty
or this:
if (“”.Equals(s))
//empty
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:
if (s.Length==0)
//empty
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:
if (string.IsNullOrEmpty(s))
//empty
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);
}
return true;
}
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.
Thank you for your support.