What is the difference between managed and unmanaged code?
Quick Answer
Managed code runs under the CLR, which handles memory, type safety and exceptions — normal C#/.NET code. Unmanaged code runs directly on the OS with no CLR services — C/C++ libraries, COM components, OS handles, file/socket handles. When managed code uses unmanaged resources it must release them explicitly via IDisposable/Dispose(), because the GC doesn't know about them.
Managed code is code the CLR runs and looks after — memory, type checks, exceptions. Unmanaged code runs straight on the operating system with none of that — think C++ libraries, COM, or OS handles for files and sockets. The practical consequence is memory: the garbage collector only knows about managed objects, so if I open something unmanaged like a file handle or a DB connection, I have to release it myself. That's what IDisposable and the using statement are for — deterministic cleanup. If I'm holding a raw handle I'd use SafeHandle rather than writing a finalizer.
The GC tracks managed memory only. An unmanaged resource — a Win32 file handle, a database connection, a GDI object — is just a number to the CLR. If you don't release it, it leaks until the process ends (or a finalizer eventually runs, which is non-deterministic).
The pattern:
- Wrap the unmanaged resource in a class that implements
IDisposable. - Callers use
usingsoDispose()runs deterministically. - Provide a finalizer as a backstop only if you hold the raw handle directly (prefer
SafeHandle, which handles this for you).
Calling into unmanaged code is done via P/Invoke ([DllImport]) or COM interop; the CLR marshals data across the boundary.