Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not possible to use both readonly and fixed-size buffers in structs in C# 7.2

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.
}
like image 624
Fit Dev Avatar asked Nov 08 '22 13:11

Fit Dev


1 Answers

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*`?
like image 137
Evk Avatar answered Nov 14 '22 22:11

Evk