Unsafe Code in .NET

Download c# eBook

Remarks

  • 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;
        }
    }
}

Related Examples

Stats

163 Contributors: 12
Wednesday, July 19, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook