Safe and Unsafe Mode Concept in C#

Introduction 
 
How does Visual Studio behave if I directly use the pointer in C#?
 
 
 
Basically this error occurred due to our .NET framework, especially CLR, which doesn't allow us to deal with "unmanaged" code directly. Right now, we have written this piece of code in Managed mode. 
 
First, we need to be clear with the concept of Managed Code and Unmanaged code in C#.
 
Managed code is the code that executes under the supervision of the CLR. The CLR is responsible for various housekeeping tasks, like:
  • Managing memory for the objects
  • Performing type verification
  • Doing garbage collection
Unmanaged Code
 
Unmanaged code is code that executes outside the context of the CLR. The best example of this is our traditional Win32 DLLs like kernel32.dll and user32.dll.
 
In unmanaged code, a programmer is responsible for:
  • Calling the memory allocation function
  • Making sure that the casting is done right
  • Making sure that the memory is released when the work is done
Now to understand what UnsafeMode is.
 
Unsafe is a C# programming language keyword to denote a section of code that is not managed by the Common Language Runtime (CLR) of the .NET Framework, or unmanaged code. Unsafe is used in the declaration of a type or member or to specify a block code. When used to specify a method, the context of the entire method is unsafe.
 
To maintain type safety and security, C# does not support pointer arithmetic, by default. However, using the unsafe keyword, you can define an unsafe context in which pointers can be used.
 
How to write your code in Unsafe mode in C#:
  • Go to View in Visual Studio
  • Then go to Solution Explorer
  • Double click on "Properties"
  • Select Build. You can see the checkbox for "Allow unsafe code". Tick it.
Once you tick this checkbox, your error under the Main method will be gone and your code will be automatically compilable without any issue.
 
Now, your C# coding is ready to take unsafe (unmanaged) code.
 
Let's see an example that will deal with unsafe code and using the pointer in C#.
 
 
 
Output