Wednesday, October 3, 2012

How do you test if a string is null or empty?

Today as I was studying something related to Asp.Net I got to an example where I had to test if a string variable is null or just an empty string. So, which are the possibilities and which is the most efficient?

  • if(myString == String.Empty)
  • if(myString == "")
  • if(myString.Length == 0) - this could throw an exception if myString is null
  • I also found this comparison: if( String.Equals(myString, String.Empty) )
  • and of course method IsNullOrEmpty introduced in .Net Framework 2:
    if(string.IsNullOrEmpty(myString)) which is said to be the most efficient.
Now, which methods do you use when comes to test if a string has a value or not? You are invited to write them as comments :) Of course that no matter which one of the methods above you choose won't slow down to much the performance of your application, but is good to build a good practice for future projects, isn't it?


  1. Vezi ca string.IsNullOrEmpty este o metoda

    if (string.IsNullOrEmpty(myString))

    1. Thanks Ionut for your reply, this is what it happens when you don't verify the code :) I have changed now the post. Regards.

    2. You're welcome. Keep up the good work ;)