Detect empty strings by using the string.IsNullOrEmpty method. Strings are reference objects and can be null like any other reference type. Strings can also be empty, meaning they equal "" and have a Length of 0.
There are several ways we can approach this problem. When I started, my approach was to test against the empty string "". That works well, but is not ideal. Next I will show you in code how to use string.IsNullOrEmpty, and I then I will share some key points.
/// <summary>
/// This method does some tests on strings and shows the basic syntax
/// for IsNullOrEmpty.
/// </summary>
static void TestStringNull()
{
string s = null;
if (string.IsNullOrEmpty(s) == true) // IsNullOrEmpty is a static method on string
{
// this block is reached because the string is null.
Console.WriteLine("String is null or empty");
}
else
{
Console.WriteLine("String has something in it");
}
string y = "";
if (string.IsNullOrEmpty(y) == true)
{
// this block is reached because the string is empty.
Console.WriteLine("String is null or empty");
}
else
{
Console.WriteLine("String has someone home");
}
string z = "sam";
if (string.IsNullOrEmpty(z))
{
// this block is NOT REACHED
Console.WriteLine("String is nothing");
}
else
{
// string is set to a value, so IsNullOrEmpty is false.
Console.WriteLine("String is set to something substantial");
}
}
The next example shows three ways of doing the same thing that IsNullOrEmpty does. Be careful to note how the string is tested against null before checking its length--null references are always a bad thing. After the next code block, I will provide a benchmark of how they perform.
/// <summary>
/// Shows three different ways to approach the problem.
/// </summary>
static void ThreeVersions()
{
string s = "";
// Test null and empty version 1.
if (s == null || s == "")
{
Console.WriteLine("Null or empty");
}
// Test version 2.
if (string.IsNullOrEmpty(s))
{
Console.WriteLine("Null or empty");
}
// Test version 3.
if (s == null || s.Length == 0)
{
Console.WriteLine("Null or empty");
}
}
| Version Benchmarked |
Time elapsed in ms 160,000,000 iterations 2.4 GHz Core 2 |
| Version 1 | 733 |
|
Version 2 IsNullOrEmpty |
546 |
| Version 3 | 406 |
string.IsNullOrEmpty provides us with a good and relatively efficient method of checking whether a string is okay to save or use. However, for serious performance binds, it may be better to use manual null checks. In the benchmarks I created, the JIT compiler may be doing something different than in normal cases that may skew the results.