简体   繁体   中英

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.
}

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*`?

The C# documentation never explicitly says this, so I'm extrapolating here.

One simple reason really: C# doesn't require you to call a constructor to initialize a struct . You can simply declare it then assign values to all its public members. (Before you ask, yes, it's mandatory to assign all of them or you'll get a compiler error.)

Since constructors / new aren't mandatory, readonly variables aren't allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM