Unsafe Code

Definition

Inside an unsafe block, C# can take the address of a value, do pointer arithmetic, and read or write memory directly without the runtime checking bounds or types. It is used for performance-critical work, interop with native buffers, and low-level memory operations the regular language does not allow.

Relevance

Unsafe code is for work the safe language cannot express cheaply: walking a native buffer, talking to a plugin that hands you a pointer, or processing bytes without a new array per step. A mistake writes past the buffer or uses a pointer after it is freed, so the block stays small and tested.

Example

A texture upload pins a byte array and passes the pointer to a native encoder. The encoder reads the pixels in place. No second copy is allocated, and the pin is released when the call returns.

Connected