Unsafe Code in .NET
suggest changeRemarks
- In order to be able to use the
unsafe
keyword 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
unsafe
).
For instance, when you use a for loop an array like so:
for (int i = 0; i < array.Length; i++)
{
array[i] = 0;
}
.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
{
fixed (int* ptr = array)
{
for (int i = 0; i <= array.Length; i++)
{
*(ptr+i) = 0;
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents