Managed code vs Unmanaged code in C#

Unmanaged Code

  • Applications that are not under the control of the CLR are unmanaged

  • The unsafe code or the unmanaged code is a code block that uses a pointer variable.

  • The unsafe modifier allows pointer usage in unmanaged code.

Let us see the example −


static unsafe void Main(string[] args) {
   int var = 20;
   int* p = &var;
   Console.WriteLine("Data is: {0} ", var);
   Console.WriteLine("Address is: {0}", (int)p);

Managed Code

Managed code is a code whose execution is managed by Common Language Runtime. It gets the managed code and compiles it into machine code. After that, the code is executed.The runtime here i.e. CLR provides automatic memory management, type safety, etc.

Managed code is written in high-level languages run on top of .NET. This can be C#, F#, etc. A code compiled in any of this language with their compilers, a machine code is not generated. However, you will get the Intermediate Language code, compiled and executed by runtime

C/C++ code, called "unmanaged code” do not have that privilege. The program is in binary that is loaded by the operating system into the memory. Rest, the programmer has to take care of.