Unsafe Code, Pointers & Fixed Buffers
Use the unsafe keyword, work with pointers, pin managed memory with fixed, and access fixed-size buffers in structs.
What Is Unsafe Code?
C#'s unsafe keyword unlocks direct memory manipulation: raw pointers, pointer arithmetic, and fixed-size buffers. It bypasses the GC safety guarantees. Enable it with <AllowUnsafeBlocks>true</AllowUnsafeBlocks> in your project file.
// Must add to .csproj:
// <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
// Unsafe blocks can appear inside methods:
unsafe
{
int x = 42;
int* ptr = &x; // get address of x
Console.WriteLine(*ptr); // dereference — prints 42
*ptr = 100;
Console.WriteLine(x); // 100 — x was mutated via pointer
}Pointer Types in C#
Pointer syntax mirrors C/C++: T* is a pointer to T. You can declare pointers to unmanaged value types (int, double, structs with no reference fields). Pointers to managed types are not allowed.
unsafe
{
int i = 10;
double d = 3.14;
int* ip = &i;
double* dp = &d;
// Dereference with *
Console.WriteLine(*ip); // 10
// Pointer arithmetic — move to next int in memory
int[] arr = { 1, 2, 3 };
fixed (int* p = arr)
{
Console.WriteLine(*(p + 0)); // 1
Console.WriteLine(*(p + 1)); // 2
Console.WriteLine(*(p + 2)); // 3
}
}All lessons in this course
- P/Invoke Fundamentals
- LibraryImport & Source-Generated P/Invoke
- Unsafe Code, Pointers & Fixed Buffers
- COM Interop & Runtime Callable Wrappers