String.IsNullOrEmpty

Might be some of you already using this. But for others it could be a great utility method.

We use a method 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 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 trim 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.

As most of aware that the beauty of the extension methods that were introduced in c#3.0. So we can have a extension method over a string, which actually does the both first trimming and then checking for IsNullOrEmpty.

So we can have the extension method as

public static bool IsNullorEmpty(this String val)
 {
 if (val != null)
 {
 if (string.IsNullOrEmpty(val.Trim()))
 return true;
 else
 return false;
 }
 return true;
 }

Lets see both existing and our new method running.

My code is

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 as.

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 existing IsNullorEmpty has been resolved in .NET 4.0. Means you don’t need to do all this. There is a new method String.IsNullOrWhiteSpace will do the both for you. But unlikely, most of us still working on .NET2.0/3.5

Hope you all must have liked it.

Leave a comment