Unsafe Code in C#
In C#, the majority of memory management tasks that a C++ programmer would
need to worry about are taken care of automatically. The thorough garbage
collection in C# (and the .NET Framework), along with the extensive use of
references, means that the C# programmer can write powerful code yet remain
totally oblivious to memory management.
However, there are times when it would be useful to have direct access to the
memory in order to be able to write code that is more powerful and versatile
than regular code. This kind of code is known as unsafe code.
Disadvantages of Unsafe Code
Using unsafe code leads to code that is more complex than regular C# code.
Unsafe code is harder to use than safe code. Using unsafe code makes it easy to
do things that aren’t good, like overwrite variables, access memory areas that
don’t contain data, or cause a stack overflow.
Unsafe code is a lot harder to debug.
Code which is using pointers is much more likely to hang or crash than safe
Advantages of Unsafe Code
Performance gain. Using pointers is the fastest and more efficient way to access
and manipulate data.
Using unsafe code allows you to retrieve the memory addresses of data by using
pointers. There is no way to do this using safe code.
Unsafe code also allows C# programs to maintain compatibility with old Windows
APIs or third-party DLL files that make use of pointers. There are ways of
accomplishing this without pointers (such as using DLL Importdeclarations), but
it’s usually simpler to use pointers.