Fix array span constructors in C##105950
Conversation
|
There is a difference between a Span created from a null array and an empty array: SharpLab int[]? array1 = null;
int[] array2 = [];
Span<int> span1 = array1;
Span<int> span2 = array2;
Console.WriteLine(span1 == null); // Prints 'True'
Console.WriteLine(span2 == null); // Prints 'False'So the null check is not redundant and was added on purpose to catch cases where the user passes a null array. Also, changing parameter types breaks compatibility. |
I didn't know this. |
|
Nevermind @raulsntos I closed this too early. I think you have gotten confused here. using System;
Span<int> span = [];
Console.WriteLine(span == null); // Prints 'True'In C#, converting a null array to a span always creates an empty but usable span. See the code: |
|
Hi. You're absolutely right that spans created from null arrays are functionally identical to spans created from empty arrays. I imagine what raulsntos was going for is that they can still be differentiated, and thus, we might want to purposefully design the API to not accept spans created from null arrays as a valid argument here. For me, it's a matter of looking at how the BCL handles this kind of cases, and stick to it as long as it makes sense. I personally can't think of a method anywhere that'd treat both cases differently. Even this atrocity is valid C# code: byte[] array = ((Span<byte>)null).ToArray();And So, long story short, I think we can merge this PR. I'm not entirely sure how breaking this is in terms of compatibility, since any previous call to |
Changing the parameter type from Changing the name of the parameter from We have to keep the |
@raulsntos I added back the old constructors as deprecated and hidden, to be removed in the next major version of Godot. Let me know if you want something else. |
|
I don't think there's a reason to deprecate them, it will produce warnings when constructing from |
Ideally this would be a good case for OverloadResolutionPriorityAttribute but GodotSharp is targeting .NET 8.0. Removing the deprecations. |
780334b to
14783cd
Compare
raulsntos
left a comment
There was a problem hiding this comment.
The .NET team discussed this PR and we think it's fine now, but we want to make sure it gets enough testing.
|
Thanks! |
…nstructors Fix array span constructors in C#

Fixes the
Span/ReadOnlySpanconstructors forGodot.Collections.Arrayin C#.The following code:
Throws:
The reason is that the constructors erroneously assume that
Span/ReadOnlySpanare nullable, and thatnullchecks are necessary. In fact, they are not only not nullable, making these checks redundant, but there is an implicit cast from arrays to spans, meaning castingnullto aSpan/ReadOnlySpanactually creates an empty span. Sospan == nullis the same asspan.IsEmpty.I also took the opportunity to normalise the use of
ReadOnlySpanrather thanSpanto allow read-only spans, addscopedto make it clear thatstackallocis allowed, and renamed the parameter for clarity.