DotNetSlackers: ASP.NET News for lazy Developers

Friday, January 7, 2011

String.IsNullOrEmpty


Maybe some of you are already using this. But for others, it could be a great utility method.
We use a static method IsNullOrEmpty of string in most of our daily task/projects a lot. It works fine in most of the cases, but it could work bizarre in some cases if not handled properly.
Say, you get a entry from UI, and having a check whether user has entered something or not. It would work fine as long as user enters the data or not.
But what happen if user enters just spaces. This method would return false, ironically this method is behaving as coded. But do we need this?
Obviously not, spaces could lead to wrong entry in our database even can corrupt the data and leads to uncommon results/Y SODS/malfunctioning.
Although being a good developer, one always trims the input before having the check. But it also tends a lots of extra LOCs which we can save and can make our system less error prone.
Most of us are aware of the beauty of the extension methods that were introduced in C# 3.0. So we can have an extension method over a string, which actually does both; first trimming and then checking for IsNullOrEmpty.
So we can have the extension method as:
 Collapse
public static bool IsNullorEmpty(this String val)
 {
      if (val != null)
      {
          if (string.IsNullOrEmpty(val.Trim()))
              return true;
          else
              return false;
      }
      return true;
 }
One more smarter code would be
 Collapse
public static bool IsNullorEmpty(this String val)
 {
      if (val != null)
      {
          return string.IsNullOrEmpty(val.Trim());
      }
      return true;
 }
Let's see both the existing and our new method running.
My code is:
 Collapse
static void Main(string[] args)
 {
     string name = "   ";
     Console.WriteLine(String.IsNullOrEmpty(name));
     Console.WriteLine(name.IsNullorEmpty());
     Console.ReadKey();
 }
The output is:
Output
But if you are still using .NET 2.0, you can have a normal static method in your utility call, which does the job for us.
 Collapse
public static bool CheckNullorEmpty(string val)
 {
     if (val != null)
     {
         if (string.IsNullOrEmpty(val.Trim()))
             return true;
         else
             return false;
     }
     return true;
 }
Note: I must say, the limitation of the existing IsNullorEmpty has been resolved in .NET 4.0. It means you don’t need to do all this. There is a new method String.IsNullOrWhiteSpace will do both for you. But unlikely, most of us are still working on .NET2.0/3.5.

No comments:

Post a Comment