-
Notifications
You must be signed in to change notification settings - Fork 4.9k
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
Passing null to an method that takes a ReadOnlySpan<T> throws, but default(ReadOnlySpan<int>) does not #23725
Comments
Should the implicit operation call an internal constructor which returns default(Span) when the array is null instead of throwing? The implicit cast would also throw if there is an array mismatch. What should we do in that scenario? static void Main(string[] args)
{
string[] a = { "Hello" };
ReadSpanLength(a); // Throws System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.
}
public static void ReadSpanLength(Span<object> span)
{
Console.WriteLine(span.Length);
} |
Yeah, I think this is reasonable, i.e. the cast should result in empty memory |
Even for array type mismatch? |
I would not change the ctor; just the cast operator. In the cast operator, there is no possibility of mismatch (as the type of the span is inferred from the array), is there? |
What about array covariance (from the code snippet I posted above)? object[] array = new String[10]; cc @jkotas |
keep going, i.e. how do I get to be casing null? |
In the code snippet, there is no null casting, but it still goes against the guideline that @ericstj mentioned since an implicit cast (from string[] to Span<object>) is resulting in an exception being thrown. |
Similar issue to https://github.com/dotnet/coreclr/issues/14012 on ArraySegments |
I think casting nulls, comparing nulls, etc. should just work and we can make it work. I don't believe there is a solution to the covarinace issue, i.e. object[] array = new String[10];
Span<object> s = array; will always fail and we cannot make it not fail. |
What if you delayed the co-variance exception to access instead of in the constructor? Do you think it would be a more intuitive failure, or do you think this is a case where we have to break the rule (you wrote I believe 😉) about throwing from implicit cast. |
I think we need to break the rule. |
Its the Exception that proves the rule 😉 (assuming that translates and is not just a nonsensical British phrase) |
That would be an awsome annotation to the design guideline :-) |
I do think we need some guidelines for Span/Memory as well. |
This is because default(ReadOnlySpan) results in a zero-length span, null is treated as a T[] which is implicitly converted to ReadOnlySpan and triggers a null check in the constructor.
It's non-intuitive for an implicit operator to throw. It violates the API design guidelines as well:
/cc @ahsonkhan @KrzysztofCwalina
The text was updated successfully, but these errors were encountered: