-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Warn when comparing spans to null #84265
Comments
Tagging subscribers to this area: @dotnet/area-system-runtime Issue DetailsThe following code var array = new char[0];
var span = array.AsSpan();
var emptyArray = Array.Empty<char>();
var emptySpan = Span<char>.Empty;
if (array == null)
Console.WriteLine("array is null");
else
Console.WriteLine("array is not null");
if (span == null)
Console.WriteLine("span is null");
else
Console.WriteLine("span is not null");
if (emptyArray == null)
Console.WriteLine("emptyArray is null");
else
Console.WriteLine("emptyArray is not null");
if (emptySpan == null)
Console.WriteLine("emptySpan is null");
else
Console.WriteLine("emptySpan is not null"); outputs the following:
The only surprising one is Spans can be compared to if (Span<char>.op_Equals(emptySpan, (Span<char>)((char[])null)))
Console.WriteLine("emptySpan is null");
else
Console.WriteLine("emptySpan is not null"); The empty span is defined as the null literal converted to a span, so this resulting in true is, albeit surprising, sensible and by design. This effectively hides the built-in diagnostic CS8073 against comparing value types to More context on Twitter.
|
#76735, I thought the plan was to add MemoryExtensions.ReferenceEqual and mark Span.Equals as obsolete/hide from intelisense? |
Maybe also a warning if you set a
This is one more reason that users could think |
Looks like that got closed in favor of #54794. I'm not sure whether this issue is now a dupe or related.
Good point! |
We should warn for any comparison against spans and memories (
It seems we don't have consensus on this view point. We should discuss this with once we have quorum again. |
We should warn for any comparison against spans and memories involving the
Category: Usage |
The following code
outputs the following:
The only surprising one is
Span<char>.Empty == null
resulting intrue
.Spans can be compared to
null
because there is an implicit conversion from arrays to spans and thenull
literal can be converted to an array, so the compiler ends up emitting this:The empty span is defined as the null literal converted to a span, so this resulting in true is, albeit surprising, sensible and by design.
This effectively hides the built-in diagnostic CS8073 against comparing value types to
null
. We should consider adding a diagnostic for comparisons between spans andnull
.As pointed out, this should probably also result in a warning:
More context on Twitter.
The text was updated successfully, but these errors were encountered: