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
Managed code vs Unmanaged code in C#
In C#, code can be categorized as either managed or unmanaged based on how it is executed and controlled by the .NET runtime environment. Understanding the difference is crucial for C# developers working with system-level programming or interoperability scenarios.
Managed Code
Managed code is code whose execution is managed by the Common Language Runtime (CLR). The CLR provides automatic memory management, type safety, exception handling, and garbage collection. When you write C# code, it is compiled into Intermediate Language (IL) code, which is then executed by the CLR.
Example of Managed Code
using System;
class ManagedExample {
public static void Main(string[] args) {
// This is managed code - CLR handles memory management
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
foreach (int num in numbers) {
Console.WriteLine("Number: " + num);
}
// No need to manually free memory - garbage collector handles it
Console.WriteLine("Managed code execution complete");
}
}
The output of the above code is −
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Managed code execution complete
Unmanaged Code
Unmanaged code is code that runs outside the control of the CLR. It includes code that uses pointers, direct memory access, or calls to native APIs. In C#, unmanaged code is written using the unsafe keyword and requires manual memory management.
Syntax
To use unmanaged code with pointers, you need the unsafe keyword −
unsafe {
int* pointer = &variable;
// pointer operations
}
Example of Unmanaged Code
using System;
class UnmanagedExample {
public static unsafe void Main(string[] args) {
int var = 20;
int* p = &var; // Pointer to the variable
Console.WriteLine("Data is: {0}", var);
Console.WriteLine("Address is: {0}", (long)p);
Console.WriteLine("Value via pointer: {0}", *p);
// Modify value through pointer
*p = 50;
Console.WriteLine("Modified data: {0}", var);
}
}
The output of the above code is −
Data is: 20 Address is: 2094639748 Value via pointer: 20 Modified data: 50
Comparison of Managed vs Unmanaged Code
| Feature | Managed Code | Unmanaged Code |
|---|---|---|
| Execution Control | Controlled by CLR | Directly by operating system |
| Memory Management | Automatic (Garbage Collector) | Manual (programmer responsible) |
| Type Safety | Type-safe by default | No type safety guarantees |
| Performance | Slight overhead due to CLR | Direct execution, potentially faster |
| Error Handling | Structured exception handling | Manual error checking required |
| Interoperability | Easy with .NET languages | Required for native API calls |
Using Mixed Code
C# applications can combine both managed and unmanaged code when needed, such as when calling native Windows APIs or working with legacy C++ libraries −
using System;
using System.Runtime.InteropServices;
class MixedCodeExample {
// Import unmanaged function from kernel32.dll
[DllImport("kernel32.dll")]
public static extern uint GetTickCount();
public static void Main(string[] args) {
// Managed code
Console.WriteLine("This is managed code");
// Call to unmanaged code
uint uptime = GetTickCount();
Console.WriteLine("System uptime (unmanaged call): {0} ms", uptime);
// Back to managed code
TimeSpan time = TimeSpan.FromMilliseconds(uptime);
Console.WriteLine("Uptime formatted: {0} days, {1} hours",
time.Days, time.Hours);
}
}
The output will vary based on system uptime −
This is managed code System uptime (unmanaged call): 1234567 ms Uptime formatted: 0 days, 0 hours
Conclusion
Managed code runs under CLR control with automatic memory management and type safety, while unmanaged code operates directly with the operating system using pointers and manual memory management. Most C# development uses managed code, but unmanaged code is essential for system-level programming and native API integration.
