C# Language Unsafe Code in .NET

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any C# Language Question?