C#idiomatic C#
ca1820fundamentals/code-analysis/quality-rules

Code analysis

CA1820: Test for empty strings using string length

Learn about code analysis rule CA1820: Test for empty strings using string length

CA1820 Performance enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

A string is compared to the empty string by using System.Object.Equals.

Rule description

Comparing strings using the System.String.Length property or the System.String.IsNullOrEmpty method is faster than using System.Object.Equals. This is because System.Object.Equals executes significantly more CIL instructions than either System.String.IsNullOrEmpty or the number of instructions executed to retrieve the System.String.Length property value and compare it to zero.

For null strings, System.Object.Equals and <string>.Length == 0 behave differently. If you try to get the value of the System.String.Length property on a null string, the common language runtime throws a System.NullReferenceException. If you perform a comparison between a null string and the empty string, the common language runtime does not throw an exception and returns false. Testing for null does not significantly affect the relative performance of these two approaches. When targeting .NET Framework 2.0 or later, use the System.String.IsNullOrEmpty method. Otherwise, use the System.String.Length == 0 comparison whenever possible.

How to fix violations

To fix a violation of this rule, change the comparison to use the System.String.IsNullOrEmpty method.

When to suppress warnings

It's safe to suppress a warning from this rule if performance is not an issue.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA1820
// The code that's violating the rule is on this line.
#pragma warning restore CA1820

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA1820.severity = none

For more information, see How to suppress code analysis warnings.

Example

The following example illustrates the different techniques that are used to look for an empty string.

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1820.cssnippet1

csharp
using System;

namespace ca1820
{
    //<snippet1>
    public class StringTester
    {
        string s1 = "test";

        public void EqualsTest()
        {
            // Violates rule: TestForEmptyStringsUsingStringLength.
            if (s1 == "")
            {
                Console.WriteLine("s1 equals empty string.");
            }
        }

        // Use for .NET Framework 1.0 and 1.1.
        public void LengthTest()
        {
            // Satisfies rule: TestForEmptyStringsUsingStringLength.
            if (s1 != null && s1.Length == 0)
            {
                Console.WriteLine("s1.Length == 0.");
            }
        }

        // Use for .NET Framework 2.0.
        public void NullOrEmptyTest()
        {
            // Satisfies rule: TestForEmptyStringsUsingStringLength.
            if (!String.IsNullOrEmpty(s1))
            {
                Console.WriteLine("s1 != null and s1.Length != 0.");
            }
        }
    }
    //</snippet1>
}