0

C#, check if a string is null or empty

Posted December 7th, 2009 in .NET, Development, Tips and Tricks by Sam Beauvois

In C# you can check if a string is null or empty in many ways :

string String1 = "testString";
if (String1== null || String1 == "")
{
// ...
}
else
{
// ...
}

string String1 = "testString";
 if (String1 == null || String1.Length==0)
 {
 // ...
 }
 else
 {
 // ...
 }
 string String1 = "testString";
 if (string.IsNullOrEmpty(String1))
 {
 // ...
 }
 else
 {
 // ...
 }

The last one is more readable.

But what about performances ?

Check this code :

private void CheckForNullOrEmpty()
 {
 int maxIterations = 9999999;

 Console.WriteLine("if (string.IsNullOrEmpty(String1))");
 Stopwatch watch = Stopwatch.StartNew();
 for (int i = 0; i < maxIterations; i++)
 {
 string String1 = "testString";
 if (string.IsNullOrEmpty(String1))
 {
 // ...
 }
 else
 {
 // ...
 }
 }

 watch.Stop();
 Console.WriteLine("\tTime : " + watch.Elapsed.TotalMilliseconds);
 Console.WriteLine(Environment.NewLine);

 Console.WriteLine("if (String1== null || String1 == \"\"");
 watch = Stopwatch.StartNew();
 for (int i = 0; i < maxIterations; i++)
 {
 string String1 = "testString";
 if (String1 == null || String1 == "")
 {
 // ...
 }
 else
 {
 // ...
 }
 }

 watch.Stop();
 Console.WriteLine("\tTime : " + watch.Elapsed.TotalMilliseconds);
 Console.WriteLine(Environment.NewLine);

 Console.WriteLine("if (String1 == null || String1.Length==0)");
 watch = Stopwatch.StartNew();
 for (int i = 0; i < maxIterations; i++)
 {
 string String1 = "testString";
 if (String1 == null || String1.Length == 0)
 {
 // ...
 }
 else
 {
 // ...
 }
 }

 watch.Stop();
 Console.WriteLine("\tTime : " + watch.Elapsed.TotalMilliseconds);
 Console.WriteLine(Environment.NewLine);

 Console.WriteLine(Environment.NewLine);
 Console.WriteLine("Press any key to continue");
 Console.ReadLine();
 }

Output is :

CheckStringForNullOrEmptyOutput

The difference between “String.IsNullOrEmpty” and “check for null then for lenght” is minimal, so prefer the String.IsNullOrEmpty() wich is more readable.

As you can guess, IsNullOrEmpty performs a check for null, then a check for lenght :

If you use Reflector to inspect the String class in the mscorlib, you can see that String.IsNullOrEmpty do the same thing we do in our test :

public static bool IsNullOrEmpty(string value)
{
if (value != null)
{
return (value.Length == 0);
}
return true;
}

the “extra” time comes from the method call

Note : In .Net Framework 4.0: string.IsNullOrWhiteSpace() method appears, but I've not tested yet (link)

Leave a Reply