Monday 13 October 2008

Checking if a string is empty

In C# there are a variety of ways of checking if a string is empty. The main methods I have seen people use are:
  1. myString == String.Empty;
  2. myString == "";
  3. myString.Length == 0;
So, which is the best one to use? FxCop provides the answer in it's performance rule TestForEmptyStringsUsingStringLength.

As the name probably gives away, the most efficient method is 3. myString.Length == 0; Or alternatively we can use the String.IsNullOrEmpty() method to test that the string isn't null at the same time.

No comments: