0 0
WP Ad Inserter plugin
Read Time:1 Minute, 17 Second

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"); CreateUserOnDb(username);
} void CreateUserOnDb(string username)
{ Console.WriteLine("Created");
}

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(""); String.IsNullOrEmpty(null); String.IsNullOrEmpty(" "); String.IsNullOrEmpty("n"); String.IsNullOrEmpty("t"); String.IsNullOrEmpty("hello"); 

but also

String.IsNullOrWhiteSpace("");
String.IsNullOrWhiteSpace(null);
String.IsNullOrWhiteSpace(" ");
String.IsNullOrWhiteSpace("n");
String.IsNullOrWhiteSpace("t");
String.IsNullOrWhiteSpace("hello");

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

Conclusion

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.

More on this topic can be found here

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

🐧

Source: https://www.code4it.dev/csharptips/string-isnullorempty-isnullorwhitespace

How to initialize an array in Java Previous post How to initialize an array in Java
Recursion in Java Next post Recursion in Java

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.