Collection expressions: invalid code generated for inline array spread element
Version Used:
Steps to Reproduce:
Compile and run:
using System.Runtime.CompilerServices;
[InlineArray(3)]
struct MyArray<T>
{
T _e0;
}
class Program
{
static void Main()
{
MyArray<int> x = new();
x[0] = 1;
x[1] = 2;
x[2] = 3;
int[] y = [..x];
}
}
Actual Behavior: Exception thrown at runtime iterating spread.
Moving out as this is a fairly niche scenario. Will reconsider based on customer feedback.
I ran into this today when trying to build a IReadOnlyCollection from an inline array + some extra data.
Is this scenario understood to be broken in the way it is? If so, this really should be prevented from compiling or be fixed... currently trying to use this seemingly valid pattern is a guaranteed AVE/NRE at runtime. The contents of the inline array are accidentally being reinterpreted as a Span (first 8 bytes being the ref, next 4 being the length) which causes an immediate explosion.
https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA+ABATARgLABQGADAAQY4B0ASgK4B2ALgJYC2MlAwhKwA7MAbGFADKwgG7MwMAM4BuQoQDaASXoDm9GAEEoUAIYBPABRYAlAF1CGAMykZjKLTCNS1GLygQ1GrboOGhADehKRhpJ7M4vqMMKS0AhD0AOakrAD6wPpgANaayQoEAL6KRHbYpJykIQTh5FhY1aF14dFQpPp6RqQAvKRaAO5uHl4+mjpdJmaFLeGdAUrEFr2kODOzHZNKOMt9WOuzzbMJSclKyzKeMPoAJitKlJTzRhYHLdz0MhBClADytIxKAB1KDMWIAGXGxkusFu0yOpBKxSAA===
(see the Span<ulong>.Enumerator enumerator = ((Span<ulong>*)(&buffer))->GetEnumerator();)
The workaround is to cast the inline array to a span directly before using the spread operator e.g [..(ReadOnlySpan<ulong>)m_array]
Also ran into this myself today. This seems to sometimes cause the CLR to crash and sometimes it just silently fails without the content being added to the list.
One more report at https://github.com/dotnet/runtime/issues/107018