< /p> < /p>
< /p> < /p>
< /p>
< /p> < /p>
< /p> < /p>
< /p> < /p>
< /p> < /p>
< /p> < /p>
' kann in diesem Zusammenhang nicht verwendet werden, da es außerhalb der enthaltenden Methode entlarvt werden kann.
Code: Select all
// take your pick of:
// Span s = stackalloc[0]; // works
// Span s = default; // fails
// Span s; // fails
if (condition)
{ // CS8353 happens here
s = stackalloc int[size];
}
else
{
s = // some other expression
}
// use s here
Code: Select all
using System;
using System.Buffers;
public static class C
{
public static void StackAllocFun(int count)
{
// #1 this is legal, just initializes s as a default span
Span s = stackalloc int[0];
// #2 this is illegal: error CS8353: A result of a stackalloc expression
// of type 'Span' cannot be used in this context because it may
// be exposed outside of the containing method
// Span s = default;
// #3 as is this (also illegal, identical error)
// Span s;
int[] oversized = null;
try
{
if (count < 32)
{ // CS8353 happens at this stackalloc
s = stackalloc int[count];
}
else
{
oversized = ArrayPool.Shared.Rent(count);
s = new Span(oversized, 0, count);
}
Populate(s);
DoSomethingWith(s);
}
finally
{
if (oversized is not null)
{
ArrayPool.Shared.Return(oversized);
}
}
}
private static void Populate(Span s)
=> throw new NotImplementedException(); // whatever
private static void DoSomethingWith(ReadOnlySpan s)
=> throw new NotImplementedException(); // whatever
// note: ShowNoOpX and ShowNoOpY compile identically just:
// ldloca.s 0, initobj Span, ldloc.0
static void ShowNoOpX()
{
Span s = stackalloc int[0];
DoSomethingWith(s);
}
static void ShowNoOpY()
{
Span s = default;
DoSomethingWith(s);
}
}