What does this modifier do?
The modifier only indicates to the compiler that you will use unsafe code and therefore it must allow this code to be considered valid.
To compile a code unsafe
it is necessary to say this to the compiler with the flag /unsafe
.
The language developers wanted to give the ease of manipulating data more freely than normal C# allows, but they didn’t want it to be done without being explicit, they didn’t want it to be abused. What could even facilitate some optimizations in other points.
Note that its use changes the security features of the application and may require use in a slightly different way than normal. You may not even be able to perform in certain scenarios. The code becomes unverifiable by CLR.
Why contexts involving pointer manipulation are considered unsafe in . NET?
The raw pointer is the main unsafe mechanism of the language, but it is useful for interoperability with other languages, mainly C and also to get more performance by accessing memory directly, in the same way that C does.
Not that it is completely free and memory is no longer managed when it does, but it can misinterpret parts of data and cause unexpected results that are not normal within what is normally accepted in C#.
Depending on how it is used it is possible to open a security breach and an external data interfere with access to memory and have the problems that normally a language like C or C++ has. Although a little more limited since you can’t access arbitrary memory positions, you have to take address from an existing object.
Pointers
The pointer does not have the same access controls as other forms have, forms that make the code slower. In general the access control of array is responsible for this. Note that the Jitter can eliminate this and the speed stay the same from the use of pointers. Yet the most common scenario where it is possible to eliminate this overhead has other costs.
There is some limitation of how you can use the pointer, it cannot point to any type, only types by value are accepted (the pointer is a type by value). There is a restriction for types that have reference types as one of their members (you can point to a char
within a string
, but cannot point to a string
).
It includes the void *
which is a pointer to an unknown type, but he can’t access anything if he wants to use it to access another type needs a cast for the type to make clear the intention, which in practice makes its use safer and less useful than in C (C3 has better mechanisms).
Pointers leave the normal C#type system, so they do not inherit from the Object
and cannot be used normally.
Guys' security is relaxed, but not off.
With the advent of Span<T>
the use of pointer becomes less necessary yet. It makes use of insecure mechanism internally, so you don’t need to use.