-
This works: char* temp = stackalloc char[1024];
var assemblyInfo = new ASSEMBLY_INFO
{
pszCurrentAssemblyPathBuf = temp,
}; So why not this? var assemblyInfo = new ASSEMBLY_INFO
{
// ❌ CS8346 Conversion of a stackalloc expression of type 'char' to type 'char*' is not possible.
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
pszCurrentAssemblyPathBuf = stackalloc char[1024],
};
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This is because |
Beta Was this translation helpful? Give feedback.
This is because
stackalloc
in C# behaves differently when it's a top-level expression vs a nested expression. Previous to C# 7.2,stackalloc
was only allowed as top-level expression, and could not be nested. You can see remnants of this here: https://github.com/dotnet/csharplang/blob/master/spec/unsafe-code.md#stack-allocation. For legacy reasons, when you usestackalloc
as a variable initializer today, you get achar*
back as the natural type, and we add an implicit conversion toSpan<T>
if the thing you assign to is aSpan<T>
. However, for any other context, we do the safer thing andstackalloc
always returns aSpan<T>
, instead of aT*
. This means that in your nested object initializer,…