CS.EXPR.EQ.STR

Use String.IsNullOrEmpty to check if a string is null or empty.

This rule recommends the use of String.IsNullOrEmpty method instead of using other ways of checking for an empty string. IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is a null reference or its value is Empty. The followings will be flagged as violations:
  • Comparison between a string and an empty string ("")
  • Comparison between a string and String.Empty
  • Comparison between the length of a string and zero (0)
  • Checking to see if the length of a string is greater than or equal to one

Vulnerability and risk

String.IsNullOrEmpty is available in .NET 2.0 and above.

There is a known problem with a compiler optimization that can cause IsNullOrEmpty (and other situations where checks are used inside a loop) to behave incorrectly when called inside a loop.

Please check https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=113102 for more information.

Vulnerable code example

Copy
  using System.Data.SqlClient;
  public class Violation
  {
      public string Test(string s)
      {
          if (s == "") // Violation
          {
              return "is null or empty";
          }
         else
         {
             return s;
         }
     }
 }

Fixed code example

Copy
  public class Repair
  {
      public String Test(String s)
      {
          if (String.IsNullOrEmpty(s) == true) // Fixed
          {
              return "is null or empty";
          }
          else
         {
             return s;
         }
     }
 }