C# tip: String.IsNullOrEmpty or String.IsNullOrWhiteSpace?

Imagine this: you have created a method that creates a new user in your system, like this:

void CreateUser(string username)
    if (string.IsNullOrEmpty(username))
        throw new ArgumentException("Username cannot be empty");


void CreateUserOnDb(string username)

It looks quite safe, right? Is the first check enough?

Let's try it: CreateUser("Loki") prints Created, while CreateUser(null) and CreateUser("") throw an exception.

What about CreateUser(" ")?

Unfortunately, it prints Created: this happens because the string is not actually empty, but it is composed of invisible characters.

The same happens with escaped characters too!

To avoid it, you can replace String.IsNullOrEmpty with String.IsNullOrWhiteSpace: this method performs its checks on invisible characters too.

So we have:

String.IsNullOrEmpty(""); //True
String.IsNullOrEmpty(null); //True
String.IsNullOrEmpty("   "); //False
String.IsNullOrEmpty("\n"); //False
String.IsNullOrEmpty("\t"); //False
String.IsNullOrEmpty("hello"); //False

but also

String.IsNullOrWhiteSpace("   ");//True

As you can see, the two methods behave in a different way.

If we want to see the results in a tabular way, we have:

value IsNullOrEmpty IsNullOrWhiteSpace
"Hello" false false
"" true true
null true true
" " false true
"\n" false true
"\t" false true


Do you have to replace all String.IsNullOrEmpty with String.IsNullOrWhiteSpace? Probably yes, unless you have a specific reason to consider the latest three values in the table as valid characters.

Do you have to replace it everything?

More on this topic can be found here

👉 Let's discuss it on Twitter or on the comment section below.



Ciao! I'm Davide Bellone, a .NET software developer! Let's keep in touch on Twitter or on LinkedIn