C# is a well-optimized language—the most commonly used implementation is at least. But suppose this is not enough for you. For your important project you want to be able to manipulate pointers and raw memory directly. In this case you can use unsafe
code blocks.
Keywords like fixed
and stackalloc
can make programs that were once easy to understand, very hard to understand. But does using these unsafe
optimizations even work—does it make programs faster? It does, but only in specific, well-tested situations. For example the GetHashCode
method on string
has been implemented with unsafe
code.
In actual programs, that use strings and for
-loops, unsafe
code is of dubious benefit. In fact, I have found:
unsafe
code typically makes programs slower, due to the cost of pinning memory (which stops the garbage collector).To be blunt, I am not a fan of unsafe
code blocks in C#. In Rust, unsafe
refers to code that hasn't been proven safe, but in C# unsafe
just refers to code that manipulates raw memory with pointers. Probably the first thing to do if a C# project uses unsafe
code is to remove or rewrite the code to standard C#.