Click here to Skip to main content
15,888,454 members
Articles / Programming Languages / C#

String.IsNullOrEmpty

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
27 Dec 2010CPOL2 min read 44.1K   6   9
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:

C#
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:

C#
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:

C#
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.

C#
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.

Hope you all must have liked it.

Image 2 Image 3 Image 4 Image 5 Image 6 Image 7 Image 8 Image 9

This article was originally posted at http://brijbhushan.net/2010/12/24/string-isnullorempty

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions

 
GeneralMy vote of 5 Pin
Sudeep35026-Dec-10 19:25
Sudeep35026-Dec-10 19:25 
GeneralRe: My vote of 5 Pin
Brij27-Dec-10 6:52
mentorBrij27-Dec-10 6:52 
GeneralA bit faster one Pin
SalarSoft25-Dec-10 8:21
SalarSoft25-Dec-10 8:21 
GeneralRe: A bit faster one Pin
Brij26-Dec-10 2:21
mentorBrij26-Dec-10 2:21 
GeneralRe: A bit faster one Pin
Brij27-Dec-10 7:02
mentorBrij27-Dec-10 7:02 
GeneralRe: A bit faster one Pin
brad.ford@cudl.com27-Dec-10 7:07
brad.ford@cudl.com27-Dec-10 7:07 
GeneralRe: A bit faster one Pin
Brij27-Dec-10 7:26
mentorBrij27-Dec-10 7:26 
GeneralRe: A bit faster one Pin
brad.ford@cudl.com27-Dec-10 8:59
brad.ford@cudl.com27-Dec-10 8:59 
Brij wrote:

I didn't understand above as it is doing the same thing as original IsNullOrEmpty provided by .NET 2.0/3.5. What would we achieve from this ?


You implemented it as an extension method, which changes the syntax from:

var isEmpty = String.IsNullOrEmpty(myString);
to
var isEmpty = myString.IsNullOrEmpty();

But it does something different (checks for Whitespace), which is bad from a usability standpoint, as others using your function may not know this distinction.

Brij wrote:
You second one is good, but we need to pass extra parameter, which again a overhead and less maintainable.


In C# 3, you can use overloaded methods... (I have a habit of using default parameters instead, which kinda defeats the purpose, as you can use the new method you pointed out).

Brij wrote:
Your last approach is really good with better block of code. But what is the necessity of it when we already have String.IsNullOrWhiteSpace in .NET 4.0, so we don't need it at all as you mentioned about C# 4.0.


But if you want to use it in C# 3, you can use it as such (without the extra parameter):

public static bool IsNullorWhitespace(this String val)        
{
            return 
               String.IsNullOrEmpty(val) || 
               val.FirstOrDefault(c => !Char.IsWhiteSpace(c)) == default(char);        
}

or have two methods (one with the extra parameter overload)

Brij wrote:
Finally, I just want to say, it's the way one want to implement. The idea was, suggesting another way to solve the flaw IsNullOrEmpty till one uses .NET 4.0(As MS already rectified this).


I personally have never had a need for it, so I wouldn't call it a flaw (I honestly didn't even know it was added to 4.0). I think the MS people think long and hard before adding stuff to .NET (especially something this easy to add yourself), but there must be enough people that have requested this for them to add it at this late stage in the game.

My basic point is to not use the .Trim, as it makes a copy of the string (and on a very large string this takes a lot of time, as well as space).
GeneralRe: A bit faster one Pin
Richard Deeming4-Jan-11 9:25
mveRichard Deeming4-Jan-11 9:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.