It defines that a block of code (can be a whole method, as in the query syntax) can use language resources considered unsafe.
This is one way to ensure that the feature is not used inadvertently and also allow other parts of the code by default to have a more aggressive optimization given the safety guaranteed.
It allows the use of pointers for memory. Pointers are insecure by nature. It is possible to use arithmetic. There are some limitations, the memory remains managed by Garbage Collector, but access to memory can be done directly to the desired location without further guarantees. This can be useful to give more performance.
If you look at some . NET codes you will see their use. The class String
uses enough to achieve maximum performance.
There is also some use of interoperability where the raw pointer is more suitable, me general for performance reasons, but also by specification, typical case of COM and other Windows Apis.
When you need direct disk access (or at least memory mapped files) it is useful.
Bit map manipulation is also an important use.
You can also use fixed
to indicate to GC that an object cannot be moved (which can cause memory fragmentation problems, nothing critical, but).
Practically never use it. I never needed it. But I love knowing that the resource is available for the day you need it (I even think I have a situation that I will use).
In general the staff loves to do premature optimization, but luckily this is not a resource often abused.
Its use is only allowed with compiler directive. Another measure not to use inadvertently.
Normally a code like this requires more privileges in the security system of the.NET. The security of the code cannot be verified.
Microsoft documentation.