C# 4.0:Finding if the string contains only WhiteSpace or Null

In the the previous Versions of the C# ,To check if the string is null or empty , we do it something similar to the example stated below.

if (input == null || (input  == "")
{
      Console.WriteLine("The string is Null or Empty");
}

The method string.IsNullOrEmpty in earlier versions of C# ,enables to check for the string if it is null or empty .

Eg :
if (string.IsNullOrEmpty((input ))
{
        Console.WriteLine("The string is Null or Empty");
}

The code looked much cleaner with IsNullOrEmpty  🙂

However the method doesnot work if the string contains only whitespaces.Whitespaces refers to the characters like space, line break, tab and empty string etc.
Eg :

if (string.IsNullOrEmpty(' '.ToString()))
{
          MessageBox.Show("emptyorNull");
}

The above code will return false .We have to use the Trim() method to get it to work.

if (string.IsNullOrEmpty(' '.ToString().Trim()))
{
      MessageBox.Show("emptyorNull");
}

C# 4.0 makes it easy with the new method String.IsNullOrWhiteSpace .This method finds out if the specified string contains null, empty, or consists only of white-space characters and returns the true/false accordingly .

Eg :

string input = new String(' ', 5);
if (String.IsNullOrWhiteSpace(input))
{
       MessageBox.Show("String is Empty or Null or has only White Spaces");
}

The above example will return true.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

3 Comments

  1. pravin June 17, 2010 Reply
  2. Hari Gillala July 1, 2011 Reply
  3. C# 4.0:Finding if the string contains only WhiteSpace or Null | ProgramInDotnet August 9, 2011 Reply

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...