Managed vs Unmanaged Code in .NET
π‘ Concept Name
Managed Code vs Unmanaged Code
π Quick Intro
In .NET, code can be classified as managed or unmanaged based on how it executes and whether itβs controlled by the CLR (Common Language Runtime).
π§ Analogy / Short Story
Imagine you're living in a smart home (managed code) where systems take care of heating, lights, and security automatically. In contrast, an unmanaged home requires you to manually do everything β secure doors, regulate temperature, etc. One offers automation and safety, the other gives full control but demands more effort.
π§ Technical Explanation
- π‘οΈ Managed Code runs under the supervision of the CLR.
- π§ CLR handles memory, type safety, security, and exception handling.
- π§© Examples: C#, VB.NET code compiled to IL and run on .NET runtime.
- π οΈ Unmanaged Code runs directly on the OS without CLR support.
- βοΈ Examples: C/C++ native binaries, Windows APIs, COM components.
- π§Ή Manual memory management required in unmanaged code (malloc/free).
π― Purpose & Use Case
- β Managed Code: Web apps, APIs, and most .NET applications.
- β Unmanaged Code: Performance-critical system components, drivers.
- β Interop: .NET can use unmanaged libraries via P/Invoke or COM interop.
π» Real Code Example
πΉ Example of calling unmanaged code from managed C# using P/Invoke:
using System;
using System.Runtime.InteropServices;
class Program {
[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, int type);
static void Main() {
MessageBox(IntPtr.Zero, "Hello from unmanaged world!", "Interop", 0);
}
}

β Interview Q&A
Q1: What is managed code?
A: Code executed by the CLR with automatic memory management.
Q2: What is unmanaged code?
A: Native code that runs directly on the OS without CLR.
Q3: Can C# use unmanaged code?
A: Yes, using P/Invoke or COM Interop.
Q4: Name one benefit of managed code?
A: Automatic garbage collection.
Q5: Name one risk of unmanaged code?
A: Memory leaks due to manual allocation.
π MCQs
Q1. Which code runs under CLR?
- Native Code
- Managed Code
- Unmanaged Code
- Assembly Code
Q2. What is a key feature of managed code?
- Manual memory handling
- No error handling
- Automatic memory management
- Unsafe type casting
Q3. What is used to call unmanaged functions in C#?
- LINQ
- P/Invoke
- Entity Framework
- CLR Loader
Q4. Which language commonly produces unmanaged code?
- C#
- VB.NET
- F#
- C/C++
Q5. Which runtime handles managed code?
- JVM
- GAC
- CLR
- WPF
π‘ Bonus Insight
Interop is powerful but should be used carefully. It can introduce platform dependency and crashes if unmanaged calls are mishandled.
π PDF Download
Need a handy summary for your notes? Download this topic as a PDF!