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