Difference between managed and unmanaged code


Managed Code

  • Managed code is created by the .NET compiler.
  • It does not depend on the architecture of the target machine because it is executed by the CLR (Common Language Runtime), and not by the operating system itself.
  • CLR and managed code offer developers few benefits, like garbage collection, type checking, exceptions handling.

Unmanaged Code

  • Unmanaged code is directly compiled to native machine code and depends on the architecture of the target machine.
  • It is executed directly by the operating system.
  • In the unmanaged code, the developer has to make sure he is dealing with memory usage and allocation (especially because of memory leaks), type safety and exceptions manually.

In .NET Visual Basic and C# compiler create managed code. To get an unmanaged code, the application has to be written in C or C++.

2 responses to “Difference between managed and unmanaged code”

  1. Can you briefly tell about ‘type safety’?

  2. Type-safe code accesses only the memory locations it is authorized to access. (For this discussion, type safety specifically refers to memory type safety and should not be confused with type safety in a broader respect.) For example, type-safe code cannot read values from another object’s private fields. It accesses types only in well-defined, allowable ways.

    In C – You declare an int, cast it to char and access memory beyond int’s boundary

    int i = 10;
    char *s = (char*)i;
    print(*(s+10));

    But for C# – Types are safe

    int i = 10;
    char *s //This is invalid unless you are using unsafe context.

    Pointers are not directly supported by .NET

Leave a comment