Expose the size of a fixed buffer using sizeof
#8952
Replies: 1 comment 19 replies
-
Duplicate of #8784. Processing address and length of buffer separately is not what's done in C#. Instead, they should be passed together within a As of #8784 (comment) , there was already proposal for creating a The proposal was not active and there's no interest to fixed size buffer any more. It's just a shorthand of inline arrays. |
Beta Was this translation helpful? Give feedback.
-
Currently the size of a fixed buffer cannot be accessed at runtime, which makes it cumbersome to use APIs like
Encoding.GetString(byte* bytes, int byteCount)
that require the size at runtime.One workaround is to define a constant for the size and using that both in the fixed buffer declaration and in all other places where the size is needed, but this can be error prone and hard to enforce.
Another workaround is to use source generation, since the size can be accessed at compile-time, but this approach seems like overkill for most simple use cases.
In practice it seems that most people (including myself on occasion) just hardcode the size everywhere.
I would therefore like to propose allowing the
sizeof
operator to be used to retrieve the size of fixed buffers. The compiler will replace the call tosizeof
with a constant value at compile time so that there will be no runtime overhead. This approach should be much easier to enforce with static analysis tools and also much nicer to use than the other alternatives.Beta Was this translation helpful? Give feedback.
All reactions