In C#, unsafe things access memory directly. The "unsafe" keyword introduces a lot of complexity to programs. It is best avoided.
The unsafe context allows unsafe memory use. It is used to implement algorithms in an efficient way. This is a modifier. Often we must also enable "unsafe" code in Visual Studio.
This program adds the unsafe modifier and fixed keyword to use char
* pointers on a string
's buffer. Fixed asserts that the memory location should not be moved in memory.
string
. We need to know this only for unsafe code.using System; class Program { unsafe static void Main() { fixed (char* value = "sam") { char* ptr = value; while (*ptr != '\0') { Console.WriteLine(*ptr); ++ptr; } } } }s a m
We can also use an unsafe block inside a method. This has an equivalent result. This spaces code out and emphasizes the unsafe modifier more.
using System; class Program { static void Main() { unsafe { fixed (char* value = "sam") { char* ptr = value; while (*ptr != '\0') { Console.WriteLine(*ptr); ++ptr; } } } } }s a m
We use fixed buffers inside an unsafe context. With a fixed buffer, you can write and read raw memory without any of the managed overhead.
This operator replaces the regular allocators. This memory is freed when the enclosing function returns. Stackalloc can be useful for external DLL calls.
These examples may be helpful in understanding. They do not focus on unsafe features in particular, but rather instances where unsafe code could be used.
The best thing to do with unsafe code is to avoid it. Unsafe code makes programs slower. It makes them harder to understand.
Unsafe code is rarely needed. Its most important use is inside the .NET Framework. There it optimizes critical methods such as GetHashCode
and string
copy routines.