Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between Managed and Unmanaged code in .NET
The .NET Framework has a CLR (Common Language Runtime) that executes code written in .NET languages. CLR manages memory allocation, security, code optimization, and platform-specific conversion. In contrast, unmanaged code runs without CLR and is executed directly by the operating system.
Managed Code
Managed code is code that runs under the supervision of the CLR. The CLR provides automatic memory management (garbage collection), type safety, exception handling, and security. Code written in C#, VB.NET, and F# compiles first to IL (Intermediate Language), which the CLR then JIT-compiles to native code at runtime.
Unmanaged Code
Unmanaged code is code that runs directly on the operating system without CLR involvement. It compiles directly to native machine code. The developer is responsible for memory management, security, and error handling. Code written in C, C++, and assembly language is typically unmanaged.
Key Differences
| Feature | Managed Code | Unmanaged Code |
|---|---|---|
| Executed By | CLR (Common Language Runtime) | Operating system directly |
| Security | Built-in security provided by CLR | Developer's responsibility |
| Memory Management | Automatic (garbage collector prevents buffer overflow) | Manual (buffer overflow possible) |
| Runtime Services | GC, exception handling, type safety | None − developer handles everything |
| Compilation Output | IL (Intermediate Language), then JIT to native | Directly to native machine code |
| Low-level Access | No direct hardware access | Full low-level hardware access |
| Examples | C#, VB.NET, F# | C, C++, Assembly |
Conclusion
Managed code runs under CLR supervision with automatic memory management, security, and exception handling, making development safer and easier. Unmanaged code runs directly on the OS with full hardware access but requires the developer to manually handle memory and security, offering more control at the cost of increased complexity.
