A new feature in c# 12 are inline arrays like
[System.Runtime.CompilerServices.InlineArray(10)]
public struct Buffer
{
private object element;
}
as described here.
If I define an instance of such array like
Buffer a = new();
I would expect that something like a.Size or a.Length is defined as a property or method, but it is not.
I found this way to get the length of the buffer: ((ReadOnlySpan<double>)a).Length. Is there a more elegant way?
I would expect that something like
a.Sizeora.Lengthis defined as a property or method, but it is not.
Unfortunately at the moment there is nothing out of the box. As is written in this discussion in the csharplang:
InlineArrayis intended to be the hidden backing storage, that is not used directly. Instead, you can just wrap it freely as a span, and then get all the niceties of that higher level abstraction.
And
Honestly the only answer here should be to just cast it to a
Span<T>and then get the Length. It jumps through a few hoops but at least the runtime seems perfectly capable of folding everything and just returning the constant value.
Basically what you have already discovered:
Buffer a = new();
Console.WriteLine(((Span<object>)a).Length);
Using the range operator ([..], which is a bit more esoteric looking, but much shorter) results in the same IL code generated:
Console.WriteLine(a[..].Length);
// decompiled generated code
Console.WriteLine(<PrivateImplementationDetails>.InlineArrayAsSpan<Buffer, object>(ref buffer, 10).Length);
demo @sharplab.io
As an option you can write a source generator which will generate some extension methods for all the inline arrays.
P.S.
The "but at least the runtime seems perfectly capable of folding everything and just returning the constant value" - claim seems to be wrong based on JIT ASM produced by the sharplab.io.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With