The C# `unsafe` keyword marks code the .NET runtime cannot verify as memory-safe. Inside an `unsafe` block, code can use pointers, allocate and free memory, and call methods through function pointers. The keyword does not mean the code is inherently dangerous; it means the runtime cannot verify protections such as array bounds and permitted memory access. section 10.3.4
A C# array reference is not a C++ pointer to a physical address: the garbage collector can move the array. To copy arrays through pointers, use `fixed` to keep both arrays at their physical locations until the pointer operations finish. section 10.3.4
Listing 10.10 C# copy array using pointers instead of references
int[] CopyArray(int[] source)
{
int length = source.Length;
int[] target = new int[length]; #1
unsafe #2
{
fixed (int* pSource = source, #3
int* pTarget = target)
{
for (int i = 0; i < length; i++)
{
pTarget[i] = pSource[i]; #4
}
}
}
return target; #5
}
The array-copy listing places pointer operations inside `unsafe` and pins both arrays with `fixed` before copying elements. section 10.3.4
