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
1 using System.Data.SqlClient; 2 public class Violation 3 { 4 public string Test(string s) 5 { 6 if (s == "") // Violation 7 { 8 return "is null or empty"; 9 } 10 else 11 { 12 return s; 13 } 14 } 15 }
Fixed code example
1 public class Repair 2 { 3 public String Test(String s) 4 { 5 if (String.IsNullOrEmpty(s) == true) // Fixed 6 { 7 return "is null or empty"; 8 } 9 else 10 { 11 return s; 12 } 13 } 14 }