Skip to content

C# Unsafe Code — Complete Guide

DodaTech Updated 2026-06-24 2 min read

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.

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 unsafe only when performance profiling shows it is necessary.
  • Use fixed to pin managed objects before accessing them via pointers.
  • Use stackalloc for stack-allocated buffers in unsafe code.
  • Use Span<T> as a safer alternative to raw pointers in most cases.
  • Use Marshal class for safe interop instead of unsafe code when possible.
  • Enable unsafe code in .csproj with <AllowUnsafeBlocks>true</AllowUnsafeBlocks>.
  • Test unsafe code extensively — memory corruption bugs can be silent.

Common Mistakes with unsafe code

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

Is unsafe code faster than safe code?

For simple array operations, the JIT can eliminate bounds checks in safe code too. Unsafe code helps when the JIT cannot prove bounds, or for pointer-heavy algorithms (tree walks, custom allocators, crypto). Measure before optimizing.

Can I use unsafe code in partial trust environments?

No. Unsafe code requires full trust. In .NET Core and .NET 5+, unsafe code works with AllowUnsafeBlocks but requires the SecurityPermission for UnmanagedCode if CAS is active.

What is the difference between unsafe and fixed?

unsafe is the keyword that enables pointer types and pointer operations in a scope. fixed is a statement that pins a managed object so pointers to it remain valid. You need both: fixed inside unsafe context.

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