What does this modifier do?
The modifier only indicates to the compiler that you will use unsafe code and therefore it should allow this code to be considered valid.
To compile a unsafe
code, you have to say this to the compiler with flag /unsafe
.
Language developers wanted to give the facility of manipulating data more freely than the norm C # allows, but they did not want this done without being explicit, they did not want them to abuse it. What could even facilitate some optimizations at other points.
Note that its use changes the security features of the application and may require the use of a slightly different form than normal. You may not even be able to execute 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 insecure mechanism of the language, but it is useful for interoperability with other languages, especially C and also for more performance accessing memory directly, in the same way that C does.
Not that it is completely free and that memory can no longer be managed when it does, but it can wrongly access pieces of data and cause unexpected results that are not normal within what is usually accepted in C #.
Depending on how it is used it is possible to open a security breach and external data interfere with memory access and have the problems that normally a language like C or C ++ has. Although a little more limited since it can not access arbitrary memory locations, it has to get address of an existing object.
Pointers
The pointer does not have the same access controls as other shapes, which makes the code slower. In general, access control of array is responsible for this. Note that JITter can eliminate this and the speed remains the same as using pointers. Although the most common scenario where you can eliminate this overhead has other costs.
There is some limitation on how you can use the pointer, it can not point to any type, only value types are accepted (the pointer is a value type). There is a restriction for types that have types by reference as one of their members.
Include the void *
that is a pointer to an unknown type, but it can not access anything if you want to use it to access another type needs a cast for type to make clear the intention, which in practice makes its use more secure and less useful than in C.
Pointers come out of the normal C # type system, so they do not inherit from Object
and can not be used normally.
Type security is relaxed, but not turned off.
With the advent of Span<T>
the use of pointer becomes less needed yet.