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

Property Value
Rule ID CA2264
Title Do not compare Span<T> to null or default
Category Usage
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As warning

Cause

A Span<T> 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 IsEmpty instead.

Example

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

Span<int> span = new([1, 2, 3]);
// CA2265 violation.
if (span == null) { }
// CA2265 violation.
if (span == default) { }

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

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.

#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.

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

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

See also