stackalloc

When working with pointers, memory might have to be allocated explicitly. In C, this job is done by functions such as malloc and alloca (which is the counterpart of stackalloc). Mono and .NET provide an alternative method called stackalloc to do the job. However, when working with Mono it isn't necessary to free memory manually because everything is done by the garbage collection unless memory is allocated explicitly with the help of stackalloc.

In the next example, you can see how stackalloc can be called:

using System;

public class Demo
{
        unsafe static void Main()
        {
                string input = "Mono";
                char *a = stackalloc char[input.Length];
                char *p = a;

                foreach (char c in input)
                {
                        *p = c;
                        Console.WriteLine(*p);
                        p++;
                }
        }
}

The code in the example ...

Get Mono Kick Start now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.