C# Language Unsafe Code in .NET Unsafe Array Index

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 Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

void Main()
{
    unsafe
    {
        int[] a = {1, 2, 3};
        fixed(int* b = a)
        {
            Console.WriteLine(b[4]);
        }
    }
}

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.

Without the unsafe block, you cannot use pointers, and therefore cannot access values past the end of an array without causing an exception to be thrown.



Got any C# Language Question?