With the release of C# 7.2 there is now the ability to have readonly
structs, which in many cases can improve performance.
For one of my structs I am using a fixed-size byte array to actually hold the data. However when I marked the struct
and the byte array field readonly
, C# compiler complained that readonly
is not valid on the field. Why can't I have both fixed
and readonly
on a field in a struct
?
readonly unsafe struct MyStruct {
readonly fixed byte _Value[6]; //The modifier 'readonly' is not valid for this item.
}
Because C# specification says so (and it always did, even before c# 7.2). In 18.7.1 section, named "Fixed size buffer declarations", the following modifiers are allowed on fixed
buffer declaration:
new
public
protected
internal
private
unsafe
No readonly
here. If you think about it - it doesn't make much sense anyway, because fixed buffer size is represented by a pointer, and you cannot restict write access to a pointer. For example:
var s = new MyStruct();
byte* value = s._Value;
// how can you prevent writing to `byte*`?
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