Unsafe Code in .NET
- In order to be able to use the
unsafekeyword in a .Net project, you must check "Allow unsafe code" in Project Properties => Build
- Using unsafe code can improve performance, however, it is at the expense of code safety (hence the term
For instance, when you use a for loop an array like so:
.NET Framework ensures that you do not exceed the bounds of the array, throwing an
IndexOutOfRangeException if the index exceeds the bounds.
However, if you use unsafe code, you may exceed the array's bounds like so:
Unsafe Array Index
Running this code creates an array of length 3, but then tries to get the 5th item (index 4). On my machine, this printed
1910457872, but the behavior is not defined.
unsafe block, you cannot use pointers, and therefore cannot access values past the end of an array without causing an exception to be thrown.
Using unsafe with arrays
When accessing arrays with pointers, there are no bounds check and therefore no
IndexOutOfRangeException will be thrown. This makes the code faster.
Assigning values to an array with a pointer:
While the safe and normal counterpart would be:
The unsafe part will generally be faster and the difference in performance can vary depending on the complexity of the elements in the array as well as the logic applied to each one. Even though it may be faster, it should be used with care since it is harder to maintain and easier to break.