C# Unsafe Code — Complete Guide
In this tutorial, you'll learn about C# Unsafe Code. We cover key concepts, practical examples, and best practices.
You need to manipulate memory directly — reading from a native buffer, implementing a fast hash, or interoperating with unmanaged APIs. C# normally prevents direct pointer access. The unsafe keyword enables pointer arithmetic and direct memory access in controlled blocks.
Wrong
public void ProcessBuffer(byte[] buffer, int length)
{
// Safe but slower — bounds checking on every access
for (int i = 0; i < length; i++)
buffer[i] = (byte)(buffer[i] ^ 0xFF);
}
Output: Works. 255 copies each value and checks bounds on every iteration.
Right
public unsafe void ProcessBuffer(byte[] buffer, int length)
{
fixed (byte* ptr = buffer)
{
for (int i = 0; i < length; i++)
ptr[i] = (byte)(ptr[i] ^ 0xFF); // No bounds checking
}
}
Output: Same result. No bounds checking. Direct memory access through the pointer.
The fixed statement pins the managed array so the GC does not move it during pointer access.
public unsafe int Sum(int* ptr, int length)
{
int total = 0;
for (int i = 0; i < length; i++)
total += ptr[i];
return total;
}
Prevention
- Use
unsafeonly when performance profiling shows it is necessary. - Use
fixedto pin managed objects before accessing them via pointers. - Use
stackallocfor stack-allocated buffers in unsafe code. - Use
Span<T>as a safer alternative to raw pointers in most cases. - Use
Marshalclass for safe interop instead of unsafe code when possible. - Enable unsafe code in
.csprojwith<AllowUnsafeBlocks>true</AllowUnsafeBlocks>. - Test unsafe code extensively — memory corruption bugs can be silent.
Common Mistakes with unsafe code
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Unsafe code is used in Durga Antivirus Pro's pattern matching engine for maximum scanning performance. For more C#, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro