C# Unsafe Code β Use Pointers and Direct Memory Access
Introduction β Why Use Unsafe Code in C#
C# is designed to be a safe, managed language, meaning it automatically handles memory allocation and prevents memory corruption. However, in some casesβsuch as interfacing with unmanaged APIs, high-performance computing, or system-level programmingβyou may need direct memory access. C# supports this through unsafe code blocks.
In this guide, youβll learn:
- What unsafe code is and how to enable it
- How to use pointers and
fixedbuffers - The
unsafe,fixed, andstackallockeywords - When and why to use unsafe code responsibly
Core Concept β What Is Unsafe Code?
Unsafe code refers to C# code blocks that allow direct memory access using pointers, similar to C and C++. You can:
- Declare and use pointers
- Perform pointer arithmetic
- Fix variables in memory to prevent garbage collection from relocating them
Unsafe code must be explicitly enabled, and it bypasses .NET’s safety checks.
Enabling Unsafe Code in Your Project
In Visual Studio:
- Right-click the project > Properties > Build
- Check “Allow unsafe code”
In .NET CLI:
dotnet build -p:AllowUnsafeBlocks=true
Basic Syntax β unsafe Keyword
unsafe
{
int x = 10;
int* ptr = &x;
Console.WriteLine((int)ptr); // Memory address
Console.WriteLine(*ptr); // Value at address
}
unsafe allows pointer operations
* dereferences the pointer
& gets the memory address of a variable
Using fixed to Pin Variables
Since the garbage collector may move objects around in memory, the fixed keyword pins a variable so its address doesnβt change.
unsafe
{
int[] numbers = { 1, 2, 3 };
fixed (int* p = numbers)
{
Console.WriteLine(p[0]); // Access array via pointer
}
}
Use fixed for arrays or fields when you need a stable pointer reference.
stackalloc for Stack Allocation
The stackalloc keyword allocates memory on the stack instead of the heapβideal for short-lived buffers.
unsafe
{
int* buffer = stackalloc int[3];
buffer[0] = 100;
Console.WriteLine(buffer[0]); // Output: 100
}
Faster than heap allocation
Automatically deallocated when the method exits
Use Cases for Unsafe Code
- High-performance algorithms (e.g., image processing)
- Interop with native libraries (C/C++)
- Operating system or embedded-level programming
- Writing custom memory buffers or unmanaged data structures
Tips, Pitfalls & Best Practices
Tip: Wrap unsafe code in small, well-isolated methods.
Pitfall: Unsafe code can lead to buffer overflows, memory leaks, and undefined behavior.
Best Practice: Avoid unsafe code unless necessary. Always validate pointer access and bounds.
Summary β Recap & Next Steps
Unsafe code in C# provides low-level control when you need it, but it comes with risks and responsibility. Use it only when managed alternatives are insufficient.
Key Takeaways:
- Use
unsafeto enable pointer operations - Use
fixedto prevent variables from moving in memory - Use
stackallocfor fast, temporary memory buffers - Enable unsafe code explicitly in your project
Next up: Explore C# Multithreading to learn how to run code concurrently for better performance.
FAQ β C# Unsafe Code
What is unsafe code in C#?
Code that uses pointers and bypasses type/memory safety features.
Is unsafe code allowed by default?
No. You must enable it in project settings or use -p:AllowUnsafeBlocks=true.
Is unsafe code faster?
It can be in performance-critical scenarios, but it requires careful memory management.
Can I use unsafe code in .NET Core or .NET 5/6+?
Yes. All modern .NET versions support unsafe code if enabled.
Should I avoid unsafe code?
Yes, unless you have a strong reason (e.g., interop, performance-critical sections).
Share Now :
