Search code examples
c#keywordstackalloc

When would I need to use the stackalloc keyword in C#?


What functionality does the stackalloc keyword provide? When and Why would I want to use it?


Solution

  • From MSDN:

    Used in an unsafe code context to allocate a block of memory on the stack.

    One of the main features of C# is that you do not normally need to access memory directly, as you would do in C/C++ using malloc or new. However, if you really want to explicitly allocate some memory you can, but C# considers this "unsafe", so you can only do it if you compile with the unsafe setting. stackalloc allows you to allocate such memory.

    You almost certainly don't need to use it for writing managed code. It is feasible that in some cases you could write faster code if you access memory directly - it basically allows you to use pointer manipulation which suits some problems. Unless you have a specific problem and unsafe code is the only solution then you will probably never need this.