π 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
fixed
buffers - The
unsafe
,fixed
, andstackalloc
keywords - 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
unsafe
to enable pointer operations - Use
fixed
to prevent variables from moving in memory - Use
stackalloc
for 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 :