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
.
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
.
Remove the redundant comparison or make the code more explicit by calling IsEmpty instead.
ExampleThe 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 warningIf 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 alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4