C# .Net unsafe code and stackalloc

A demo of using unsafe code in a .Net application.

using System;

namespace CsharpUnsafeDemo
{
    class CsharpUnsafeExample
    {
        // Enable unsafe code in project settings
        static unsafe void Main()
        {
            const int length = 10;

            int* stack = stackalloc int[length];
            
            var currentVal = stack;
            
            for (var i = 0; i <= length; i++, currentVal++)
            {
                *currentVal = i;
            }
            
            for (var i = 0; i < length; i++)
            {
                Console.WriteLine(stack[i]);
            }

            Console.ReadKey();
        }
    }
}

Returns:

0
1
2
3
4
5
6
7
8
9

Leave a Reply

Your email address will not be published. Required fields are marked *