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.