DEV Community

Mariem Moalla
Mariem Moalla

Posted on

C# tips: string.IsNullOrEmpty vs string.IsNullOrWhiteSpace

When working with text in .NET, one of the most common checks we perform is:
“Does this string have a meaningful value, or is it just empty/null?”

Two helpers exist for this purpose:

  • string.IsNullOrEmpty
  • string.IsNullOrWhiteSpace At first glance, they may seem similar, but there’s an important distinction that can save you from getting bugs.

Using string.IsNullOrEmpty

This method checks if a string is either:

  • null
  • "" (an empty string)
Console.WriteLine(string.IsNullOrEmpty(null));   // true
Console.WriteLine(string.IsNullOrEmpty(""));     // true
Console.WriteLine(string.IsNullOrEmpty("   "));  // false
Console.WriteLine(string.IsNullOrEmpty("abc"));  // false
Enter fullscreen mode Exit fullscreen mode

Notice that " " (spaces only) returns false.
This means IsNullOrEmpty only guards against null or empty strings, not whitespace.

Using string.IsNullOrWhiteSpace

This method goes one step further: it considers whitespace-only strings as invalid.

Console.WriteLine(string.IsNullOrWhiteSpace(null));   // true
Console.WriteLine(string.IsNullOrWhiteSpace(""));     // true
Console.WriteLine(string.IsNullOrWhiteSpace("   "));  // true
Console.WriteLine(string.IsNullOrWhiteSpace("abc"));  // false
Enter fullscreen mode Exit fullscreen mode

Here, " " returns true because the method trims out whitespace and checks for emptiness.

Performance Consideration

Both methods are O(n) because they may scan characters (especially IsNullOrWhiteSpace).

  • IsNullOrEmpty is slightly faster since it only checks length.
  • IsNullOrWhiteSpace is marginally slower but usually negligible in real-world apps.

For example:

var str = new string(' ', 1000); // 1000 spaces

Console.WriteLine(string.IsNullOrEmpty(str));     // false
Console.WriteLine(string.IsNullOrWhiteSpace(str)); // true
Enter fullscreen mode Exit fullscreen mode

The performance difference only matters when doing millions of checks per second, which is rare in typical business applications.

Top comments (0)