IsNullOrWhiteSpace

When one deals with user input, it is quite useful to check whether user entered anything. Definition of "anything" is not necessarily same for developer and user.

Quite often user will consider one accidental space to be nothing at all. To implement proper check developer would need something like this:

if (string.IsNullOrEmpty(text) || (text.Trim().Length == 0)) {
//Text is empty.
} else {
//Text is not empty.
}

Code is not difficult and it is pretty obvious. Hard part (at least for me) is remembering to add this text.Trim().Length==0 condition. Some time I just forget.

.NET 4.0 brings little bit of syntactic sugar in this area:

if (string.IsNullOrWhiteSpace(text)) {

It is basically same code - just a little bit shorter and, thanks to IntelliSense, much easier to remember.

Leave a Reply

Your email address will not be published. Required fields are marked *