Skip to content

Commit 2a8549a

Browse files
authored
update stackalloc for Span (#808)
Because Span is much more awesome than pointers. And safer. Supports dotnet/docs#6184
1 parent bea7841 commit 2a8549a

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

snippets/csharp/keywords/StackAllocExamples.cs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ public static void Examples()
1111
InitializeBitMasks();
1212
}
1313

14-
private static unsafe void InitializeBitMasks()
14+
private static void InitializeBitMasks()
1515
{
1616
// <Snippet2>
17-
int* mask = stackalloc[] {
17+
ReadOnlySpan<int> mask = stackalloc[] {
1818
0b_0000_0000_0000_0001,
1919
0b_0000_0000_0000_0010,
2020
0b_0000_0000_0000_0100,
@@ -61,14 +61,13 @@ private static unsafe void FibonacciGeneration()
6161
{
6262
// <Snippet1>
6363
const int arraySize = 20;
64-
int* fib = stackalloc int[arraySize];
65-
int* p = fib;
64+
Span<int> fib = stackalloc int[arraySize];
6665
// The sequence begins with 1, 1.
67-
*p++ = *p++ = 1;
68-
for (int i = 2; i < arraySize; ++i, ++p)
66+
fib[0] = fib[1] = 1;
67+
for (int i = 2; i < arraySize; ++i)
6968
{
7069
// Sum the previous two numbers.
71-
*p = p[-1] + p[-2];
70+
fib[i] = fib[i-1] + fib[i-2];
7271
}
7372
for (int i = 0; i < arraySize; ++i)
7473
{

0 commit comments

Comments
 (0)