Why is a fixed size buffers (arrays) must be unsafe?

Posted by brickner on Stack Overflow See other posts from Stack Overflow or by brickner
Published on 2010-05-21T10:57:44Z Indexed on 2010/05/21 11:20 UTC
Read the original article Hit count: 363

Filed under:
|
|
|
|

Let's say I want to have a value type of 7 bytes (or 3 or 777).

I can define it like that:

public struct Buffer71
{
    public byte b0;
    public byte b1;
    public byte b2;
    public byte b3;
    public byte b4;
    public byte b5;
    public byte b6;
}

A simpler way to define it is using a fixed buffer

public struct Buffer72
{
    public unsafe fixed byte bs[7];
}

Of course the second definition is simpler. The problem lies with the unsafe keyword that must be provided for fixed buffers. I understand that this is implemented using pointers and hence unsafe.

My question is why does it have to be unsafe? Why can't C# provide arbitrary constant length arrays and keep them as a value type instead of making it a C# reference type array or unsafe buffers?

© Stack Overflow or respective owner

Related posts about c#

Related posts about fixed