Posted by  Programming  Add comments  Tagged with:
Jul 102010

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

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