Use
string.IsNullOrWhiteSpace
instead of comparing against empty string 38 var emptyString = string.Empty;
39 // CS-R1014: Use `string.IsNullOrEmpty` or `string.IsNullOrWhiteSpace` to check for empty strings.
40 // https://deepsource.io/directory/analyzers/csharp/issues/CS-R1014
41 if (emptyString == "") 42 {
43 Console.WriteLine("String is empty!");
44 }
Description
Comparing a string against an empty string literal is valid and is the preferred way in languages such as Go and Python. In C# however, it is recommended that you use the convenience methods such as string.IsNullOrWhiteSpace
or string.IsNullOrEmpty
as they offer slightly better performance when compared to other traditional/naive implementations.
Bad Practice
if (str == "")
{
Console.WriteLine("`str` is empty");
}
Recommended
if (string.IsNullOrWhiteSpace(str))
{
Console.WriteLine("str is empty");
}