In this lesson we will continue our discussion on C# pointers.
In C#, we have two modes for the code, the managed and unmanaged. The code written within the unsafe block is known as unmanaged code and all other code outside the unsafe block comes under
the definition of managed code.
- Managed code is executed under the control of Common Language Runtime (CRL).
- It has automatic garbage collection. That is, the dynamically allocated memory area which is no longer in use is not destroyed by the programmer explicitly. Rather, it is automatically reclaimed
by the built-in garbage collector.
- There is no explicit memory allocation and deallocation.
- There is no explicit call to the garbage collector as well.
The unmanaged code provides access to memory through pointers just like C++. It is useful in many scenarios. For example:
Disadvantages of Unsafe Code in C#
- Pointers may be used to enhance performance in real time applications.
- In non-.net DLLs some external functions requires a pointer as a parameter, such as Windows APIs that were written in C.
- Sometimes we need to inspect the memory contents for debugging purposes, or we might need to write an application that analyzes another application process and memory.
It is easy to see that the unmanaged code, just like C++, is potentially unsafe. Some of the difficulties arise from the fact that they have complex syntax and are harder to use.
Also, misusing pointers might lead to the problems such as accidental overwritting of other variables, illegal access to memory areas not under your control, and stack overflow.
They are also harder to debug and they also compromise type-safety.
Next >>> Lesson No. 12: C# Structs and Enums