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

Code analysis

CA2265: Do not compare `Span<T>` to `null` or `default`

Learn about code analysis rule CA2265 - Do not compare Span<T> to 'null' or 'default'

CA2264 Usage enabled by default in .NET 10: As warning
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

A System.Span instance is compared to null or default.

Rule description

Comparing a span to null or default might not do what you intended. default and the null literal are implicitly converted to Span<T>.Empty.

How to fix violations

Remove the redundant comparison or make the code more explicit by calling System.Span.IsEmpty instead.

Example

The following code snippet shows two violations of CA2265 and the fix for the violations.

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2265.cs1

csharp
using System;

namespace ca2265;
class CA2265
{
    public static void RunIt()
    {
        // <Snippet1>
        Span<int> span = new([1, 2, 3]);
        // CA2265 violation.
        if (span == null) { }
        // CA2265 violation.
        if (span == default) { }

        // Fixes the violation.
        if (span.IsEmpty) { }
        // </Snippet1>
    }
}

When to suppress warnings

It's safe to suppress this warning if you meant to compare the span to the empty span.

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 CA2265
// The code that's violating the rule is on this line.
#pragma warning restore CA2265

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

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

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

See also