Home
Blog
Unsafe Code in C#
Updated
Dot Net Perls

Unsafe Code in C#

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:

Using unsafe code typically makes programs slower, due to the cost of pinning memory (which stops the garbage collector).
The resulting code is almost always hard to maintain and debug.
More effective optimizations are typically available—have you considered a different approach or algorithm?

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#.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen