What is the difference between managed and unmanaged code?

12 minintermediate.NETmanagedunmanaged

Quick Answer

Managed code runs under the CLR's control with automatic memory management, type safety, and exception handling. Unmanaged code runs directly on the OS without CLR services, requiring manual memory management and error handling. Managed code is safer but has overhead, while unmanaged code offers direct system access and performance.

Detailed Answer

The distinction between managed and unmanaged code is fundamental to understanding how .NET applications work and how they interact with system resources and external libraries.

Managed Code:

Managed code is code that runs under the control of the Common Language Runtime (CLR). The CLR provides automatic memory management, type safety, and other services.

Characteristics of Managed Code:

  1. Automatic Memory Management

    public class ManagedExample
    {
        public void ManagedMethod()
        {
            // Memory automatically allocated
            var list = new List<int>();
            list.Add(1);
            list.Add(2);
            // Memory automatically freed by Garbage Collector
        }
    }
    
  2. Type Safety

    public class TypeSafetyExample
    {
        public void SafeOperations()
        {
            int number = 42;
            // string text = number; // Compile-time error
            string text = number.ToString(); // Explicit conversion
            
            // Runtime type checking
            object obj = "Hello";
            if (obj is string str)
            {
                Console.WriteLine(str.ToUpper()); // Safe operation
            }
        }
    }
    
  3. Exception Handling

    public class ExceptionHandlingExample
    {
        public void ManagedExceptionHandling()
        {
            try
            {
                int result = Divide(10, 0);
            }
            catch (DivideByZeroException ex)
            {
                // Structured exception handling
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
        
        private int Divide(int a, int b)
        {
            return a / b; // Throws managed exception
        }
    }
    
  4. Security

    public class SecurityExample
    {
        public void SecureOperation()
        {
            // Code Access Security (CAS) applies
            // CLR validates permissions before execution
            File.WriteAllText("test.txt", "Hello World");
        }
    }
    

Unmanaged Code:

Unmanaged code runs directly on the operating system without the CLR's management. It's typically written in languages like C, C++, or assembly.

Characteristics of Unmanaged Code:

  1. Manual Memory Management

    // C code example
    #include <stdlib.h>
    
    void unmanaged_memory_example() {
        // Manual memory allocation
        int* numbers = malloc(100 * sizeof(int));
        
        // Use the memory
        for (int i = 0; i < 100; i++) {
            numbers[i] = i;
        }
        
        // Manual memory deallocation (must not forget!)
        free(numbers);
    }
    
  2. Direct System Access

    // C code - direct system calls
    #include <windows.h>
    
    void direct_system_access() {
        // Direct Windows API call
        HANDLE file = CreateFile(
            L"test.txt",
            GENERIC_WRITE,
            0,
            NULL,
            CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            NULL
        );
        
        if (file != INVALID_HANDLE_VALUE) {
            // Use the file handle
            CloseHandle(file); // Manual cleanup
        }
    }
    
  3. No Automatic Exception Handling

    // C code - manual error handling
    int divide_numbers(int a, int b) {
        if (b == 0) {
            // Manual error handling - no exceptions
            return -1; // Error code
        }
        return a / b;
    }
    

Interop Between Managed and Unmanaged Code:

  1. P/Invoke (Platform Invoke)

    public class PInvokeExample
    {
        // Import unmanaged Windows API
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr GetCurrentProcess();
        
        [DllImport("user32.dll")]
        public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
        
        public void CallUnmanagedCode()
        {
            // Call unmanaged function from managed code
            IntPtr process = GetCurrentProcess();
            MessageBox(IntPtr.Zero, "Hello from unmanaged code!", "Message", 0);
        }
    }
    
  2. COM Interop

    public class COMInteropExample
    {
        public void UseCOMObject()
        {
            // Create COM object from managed code
            var excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible = true;
            
            // Use COM object
            var workbook = excel.Workbooks.Add();
            var worksheet = workbook.ActiveSheet;
            worksheet.Cells[1, 1] = "Hello from COM!";
            
            // Cleanup (important for COM objects)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
        }
    }
    
  3. C++/CLI (Managed C++)

    // C++/CLI code - can mix managed and unmanaged
    #include <iostream>
    #include <msclr/marshal_cppstd.h>
    
    using namespace System;
    using namespace msclr::interop;
    
    public ref class MixedCode
    {
    public:
        void ManagedMethod()
        {
            // Managed code
            String^ managedString = "Hello from managed C++";
            Console::WriteLine(managedString);
        }
        
        void UnmanagedMethod()
        {
            // Unmanaged code
            std::cout << "Hello from unmanaged C++" << std::endl;
        }
    };
    

Comparison Summary:

AspectManaged CodeUnmanaged Code
Memory ManagementAutomatic (GC)Manual (malloc/free)
Type SafetyEnforced by CLRNo enforcement
Exception HandlingStructuredManual error codes
SecurityCode Access SecurityNo built-in security
PerformanceSlight overheadMaximum performance
PlatformCross-platformPlatform-specific
DevelopmentFaster, saferMore control, more risk

Related Resources