Why does the 'stackalloc' keyword not work with properties?

狂风中的少年 提交于 2019-12-22 09:48:28

问题


I was writing some unsafe code recently in C# and noticed this produces a syntax error:

public unsafe class UnsafeByteStream
{
    public UnsafeByteStream(int capacity)
    {
        this.Buffer = stackalloc byte[capacity];
    }

    public byte* Buffer { get; }
}

The result of this is: "Invalid expression term 'stackalloc' / ; expected / } expected". However, when I assign this first to a local field, like so:

public UnsafeByteStream(int capacity)
{
    byte* buffer = stackalloc byte[capacity];
    this.Buffer = buffer;
}

Then there is no syntax error produced.

Is there a reason for this, or is something up with the compiler? I understand that pointer-type properties are not all that common, but I still don't understand why this is a syntax error as opposed to a semantic one, assuming something's wrong with the code.


回答1:


stackalloc must be part of the local variable declaration, as discussed in the documentation.

The [stackalloc] keyword is valid only in local variable initializers. The following code causes compiler errors.

int* block;
// The following assignment statement causes compiler errors. You
// can use stackalloc only when declaring and initializing a local 
// variable.
block = stackalloc int[100];

As such it truly is a syntax error; and rejects the obj.Property = stackalloc .. form.

(The later assignment to a property is an - uncaught - semantic error.)



来源:https://stackoverflow.com/questions/32343050/why-does-the-stackalloc-keyword-not-work-with-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!