C# Programming › .NET Framework Fundamentals

What are the differences between managed code and unmanaged code?

Intermediate

Answer

Managed code is code that runs under the control of the Common Language Runtime, which handles memory management through garbage collection, type safety, exception handling, and security, and all C# code compiled for dot NET falls into this category. Unmanaged code, on the other hand, runs directly on the operating system without the CLR's oversight, meaning the developer is responsible for manually managing memory allocation and deallocation, as is common in languages like C or C plus plus, which increases both flexibility and the risk of memory related bugs.
// Managed code: garbage collector handles cleanup automatically
var list = new List<int>();
// No manual memory deallocation required
Real-world example A dot NET application that needs to call into an existing C plus plus library uses Platform Invoke to bridge managed code and unmanaged code, letting the two communicate despite having very different memory management models.

Common follow-ups: What is Platform Invoke and when is it used?;Can managed code call unmanaged code directly?