CodeBlanks Logo Icon CodeBlanks

unsafe block

C# course · Expert · Lesson 7/47

Learn the unsafe block and pointer usage.

What is an unsafe block?

An unsafe block is a special code region in C# that allows pointer usage. Pointers hold raw memory addresses, which steps outside the normal C# rules.

To use unsafe, the project must enable <AllowUnsafeBlocks>true</AllowUnsafeBlocks>. An unsafe block lets you write code where the GC cannot move objects. This is preferred in performance-critical scenarios.

When is unsafe used?

unsafe code is typically used in performance-critical areas such as game engines, image processing and native library wrappers. It is rarely needed in everyday code because pointer errors can cause crashes and security holes.

Modern C# offers Span<T> and ref struct types that safely replace many uses of unsafe. So unsafe is reached for only when truly necessary.

Exercise Print a value with an unsafe method

Define an unsafe static void Touch() method. In its body write int x = 10; and int* p = &x;, then print the value with Console.WriteLine(*p);. Call Touch(); from Main.

Show example solution
unsafe static void Touch() { int x = 10; int* p = &x; Console.WriteLine(*p); }
Example solution:
using System;

class Program
{
    unsafe static void Touch()
    {
        int x = 10;
        int* p = &x;
        Console.WriteLine(*p);
    }

    static void Main()
    {
        Touch();
    }
}

Test yourself

  1. What does an unsafe block enable?

    • Pointer usage
    • Faster GC
    • Shorter code
    • Automatic memory management
    Show answer

    Pointer usage — Correct. Pointers such as int* can be used inside an unsafe block.

  2. Complete the unsafe method

    public ____ void DoWork() { int x = 5; int* p = &x; }
    Show answer
    public unsafe void DoWork() { int x = 5; int* p = &x; }
  3. What is required to use unsafe?

    • Only async
    • Only static
    • AllowUnsafeBlocks in the project
    • Nothing
    Show answer

    AllowUnsafeBlocks in the project — Correct. The AllowUnsafeBlocks project setting must be on.

All lessons in Expert