Skip to content

3.3 — Managed vs Unmanaged Code, unsafe, P/Invoke

← Roadmap · Section: 3. .NET Runtime and Platform Prev: 3.2 CLR and compilation · Next: 3.4 Garbage collection

Markers: — · Confidence: 🔴 · Last reviewed: —


TL;DR

Managed code is code the CLR runs and looks after — it handles the memory, checks the types, and catches mistakes like reading past the end of an array. Unmanaged code is everything else: C, C++, operating system calls. Nobody is watching it for you.

  • Almost all C# you write is managed. You only meet unmanaged code when calling something outside .NET.
  • P/Invoke is how you call an unmanaged function from C#.
  • unsafe lets you use raw pointers in C#. You will rarely need it.

Definitions

Term What it is in .NET What it means
Managed code code the CLR executes Your C#. The CLR handles memory, garbage collection, type safety and bounds checking.
Unmanaged code code outside the CLR Compiled C or C++, Windows API functions, native libraries. No GC, no safety checks.
Managed resource an object on the .NET heap Cleaned up automatically by the garbage collector.
Unmanaged resource something the OS gave you A file handle, socket, or window handle. The GC knows nothing about it — you must release it.
P/Invoke a mechanism Platform Invoke. Calling a function in a native .dll or .so from C#.
DllImport an attribute Marks a C# method as actually living in a native library. The classic P/Invoke syntax.
LibraryImport an attribute (.NET 7+) The modern replacement. A source generator writes the interop code at build time, so it works with AOT.
Marshalling a conversion step Translating data between .NET's layout and the native layout — for example a C# string to a C char*.
unsafe a C# keyword Allows pointer syntax (*, &) inside a block or method. Must be enabled in the .csproj.
fixed a C# statement Pins an object so the GC cannot move it while you hold a pointer to it.
Pinning what fixed does Telling the GC "do not relocate this object during compaction".
IntPtr / nint a struct A raw pointer-sized integer. How native handles are represented in C#.
SafeHandle an abstract class A wrapper around a native handle that releases it reliably. The correct way to hold one.

The concept

What "managed" actually buys you

When the CLR runs your code, it does a lot of work in the background that you never see:

  • Memory is allocated and freed for you by the garbage collector.
  • Array bounds are checked. Reading array[10] on a 5-element array throws an exception rather than silently reading whatever memory happens to be next.
  • Types are verified. You cannot treat a string as an int by lying about it.
  • Pointers are not exposed, so you cannot accidentally read freed memory.

That collection of guarantees is what "managed" means. It removes an entire category of bug — buffer overruns, use-after-free, memory corruption — that has caused a large share of the security vulnerabilities in software history.

Unmanaged code has none of that. C and C++ let you write past the end of a buffer, use a pointer after freeing it, or interpret one type as another. Faster and more flexible, and far easier to get catastrophically wrong.

A picture: managed code is driving a car with seatbelts, airbags and lane assist. Unmanaged code is a racing car with none of it. The racing car can be faster, and a small mistake is much more expensive.

Why you would ever leave the safety

Three reasons, and only three:

  1. The functionality only exists natively. Windows API calls, hardware drivers, a C library like SQLite or FFmpeg with no .NET equivalent.
  2. Extreme performance in a very narrow spot, where even the small cost of bounds checking matters. This is rare and should always be measured first.
  3. You are given a handle by the operating system — a file, socket or window — and must release it yourself.

Number three is the one that touches ordinary application code, and it is why IDisposable exists at all.


How it works

The simple version — managed vs unmanaged resources

This distinction matters far more day to day than pointers do.

public class Example
{
    private byte[] _buffer = new byte[1024];   // MANAGED — the GC frees this
    private FileStream _file;                  // holds an UNMANAGED file handle inside
}

The byte[] is a normal .NET object. When nothing references it, the garbage collector reclaims it and you do nothing.

The FileStream is also a .NET object, but inside it is a file handle given out by the operating system. The GC knows how to free the FileStream object's own memory. It has no idea what a file handle is or how to close one.

So the handle stays open — and the file stays locked — until something calls Dispose. That is the entire reason for IDisposable and using:

using var file = File.OpenRead(path);   // Dispose closes the OS handle

Covered fully in 1.21.

How it actually works — P/Invoke

To call a native function you declare it in C# and tell the runtime where it lives.

The classic form uses DllImport:

using System.Runtime.InteropServices;

public static class Native
{
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
}

Native.MessageBox(IntPtr.Zero, "Hello", "Title", 0);

Note extern and no body. You are describing a function that lives elsewhere; the runtime finds it and wires up the call.

Modern .NET prefers LibraryImport (.NET 7+), which uses a source generator to write the interop code at build time:

public static partial class Native
{
    [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)]
    public static partial int MessageBox(IntPtr hWnd, string text, string caption, uint type);
}

Two differences worth knowing: the class and method must be partial so the generator can fill them in, and because the code is generated at build time it works with Native AOT, whereas DllImport relies on runtime generation that AOT removes. See 3.2.

Marshalling is the conversion in between. A C# string is UTF-16 and length-prefixed; a C char* is a pointer to null-terminated bytes. The runtime converts, and telling it exactly how is most of the work in real interop.

The deeper detail — unsafe, pointers and pinning

unsafe lets you use C-style pointers in C#. You must opt in per project:

<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
unsafe
{
    int value = 42;
    int* pointer = &value;      // address of value
    Console.WriteLine(*pointer); // 42 — read through the pointer
}

Now the important part, and it connects directly to garbage collection.

The GC moves objects. During the compact phase it slides survivors together to remove gaps (3.4). So an object's address is not stable.

That is fine normally, because the CLR updates every reference when it moves something. But it cannot update a raw pointer — it does not know the pointer exists.

unsafe
{
    byte[] data = new byte[1024];

    fixed (byte* p = data)          // PIN it — the GC may not move it
    {
        NativeFunction(p, data.Length);
    }
    // unpinned here — the GC may move it again
}

fixed pins the object for the duration of the block. Without it, a collection mid-call could relocate the array and leave your native function writing to memory that no longer holds it — which corrupts the heap in ways that surface much later and are extremely hard to diagnose.

⚠️ Keep fixed blocks short. A pinned object cannot be moved, so it creates a hole in the heap that compaction has to work around. Long-lived pins cause fragmentation.

The right way to hold a native handle

Do not store raw IntPtr handles. Use SafeHandle:

public sealed class MyFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    public MyFileHandle() : base(ownsHandle: true) { }

    protected override bool ReleaseHandle() => CloseHandle(handle);

    [LibraryImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static partial bool CloseHandle(IntPtr handle);
}

SafeHandle gives you three things a raw IntPtr does not: guaranteed release even if the process is being torn down, protection against the handle being recycled while in use, and correct behaviour with the finalizer pattern. This is the reason you almost never need to write the full dispose pattern by hand — see 1.21.


Code

The realistic version of this in ASP.NET Core: you will almost never write any of it.

What you actually do is release unmanaged resources properly:

public class ReportService
{
    public async Task<byte[]> GenerateAsync(Guid id, CancellationToken ct)
    {
        // Every one of these holds an unmanaged resource internally:
        //   FileStream  → an OS file handle
        //   SqlConnection → a network socket
        // 'await using' releases them even if something throws.

        await using var connection = new SqlConnection(_connectionString);
        await connection.OpenAsync(ct);

        await using var output = File.Create(_tempPath);

        // ... work ...

        return await File.ReadAllBytesAsync(_tempPath, ct);
    }
}

The takeaway: managed versus unmanaged mostly reaches you as "which things do I have to dispose?" The answer is anything wrapping an OS resource — files, sockets, database connections, HTTP handlers, cryptography objects.


Interview questions

Q: What is the difference between managed and unmanaged code?

Managed code runs under the CLR, which handles memory allocation and garbage collection, verifies types, and checks array bounds — so a whole class of bugs like buffer overruns and use-after-free simply cannot happen. Unmanaged code is compiled native code such as C or C++, or operating system functions, running outside the CLR with none of those guarantees. Almost all C# is managed; you meet unmanaged code when calling into the OS or a native library, or when holding a resource the OS gave you.

Q: What is the difference between a managed and an unmanaged resource?

A managed resource is an ordinary .NET object on the heap — the garbage collector reclaims it automatically. An unmanaged resource is something the operating system handed you, like a file handle, socket or window handle. The GC can free the .NET object that wraps it, but it has no idea what the handle is or how to close it. So the file stays locked until something calls Dispose. That gap is exactly why IDisposable and using exist.

Q: What is P/Invoke?

Platform Invoke — the mechanism for calling a function in a native library from C#. You declare a method with no body marked extern, and attribute it with DllImport or, in .NET 7 and later, LibraryImport. The runtime locates the function and handles marshalling, which is converting data between .NET's representation and the native one. LibraryImport is preferred now because it uses a source generator to produce the interop code at build time, which means it works under Native AOT, whereas DllImport relies on runtime generation that AOT strips out.

Q: Why do you need the fixed statement?

Because the garbage collector moves objects. During the compaction phase it slides surviving objects together to remove gaps, and it updates every managed reference to match. It cannot update a raw pointer, because it has no idea the pointer exists. So if you take a pointer to a managed array and a collection happens mid-call, your pointer now refers to memory that no longer holds that array. fixed pins the object so the GC will not relocate it for the duration of the block. Pins should be short, because a pinned object blocks compaction and causes fragmentation.


Traps ⚠️

  • Forgetting that a managed object can hold an unmanaged resource. FileStream is a .NET object, but the file handle inside it needs disposing.
  • Taking a pointer without fixed. The GC can move the object underneath you and corrupt memory in a way that surfaces much later.
  • Long-lived fixed blocks fragment the heap, because pinned objects cannot be moved during compaction.
  • DllImport breaks under Native AOT. Use LibraryImport for anything new.
  • Marshalling mistakes are silent. Getting a struct layout or string encoding wrong reads garbage rather than throwing.
  • Raw IntPtr handles can leak or be recycled. Use SafeHandle.
  • unsafe needs enabling in the .csproj. It is off by default on purpose.


Sources