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

后端 未结 7 1104
清歌不尽
清歌不尽 2021-02-05 04:25

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

7条回答
  •  难免孤独
    2021-02-05 04:52

    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.

提交回复
热议问题