.NET › CLR & Runtime

What is the difference between managed and unmanaged code in .NET, and when would you need to work with the latter?

Beginner

Answer

Managed code runs entirely inside the CLR, which handles memory allocation/deallocation, enforces type and memory safety, and manages exceptions on the developer's behalf -- ordinary C# code is managed by default. Unmanaged code (typically C/C++) runs outside the CLR's supervision, requiring the developer to manually manage memory and accepting greater risk of leaks or crashes in exchange for tighter low-level control -- .NET developers most commonly touch unmanaged code when calling into an existing native library via P/Invoke, or bridging to legacy COM components via COM Interop.
using System.Runtime.InteropServices;

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

// Calling into unmanaged Windows API code from managed C#
NativeMethods.MessageBox(IntPtr.Zero, "Hello from native code", "P/Invoke", 0);
Real-world example A .NET application needing to call a specialized image-processing library that only ships as a native C++ DLL uses P/Invoke to bridge into that unmanaged code, while keeping the rest of the application entirely within the CLR's safer, managed world.

Common follow-ups: What specific risks does calling unmanaged code introduce that managed code doesn't have?;How does the CLR's security model change once execution crosses into unmanaged territory?