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!

➑️ Next:

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: