A C# array holds a fixed number of indexed elements. Create one with `new int[count]`, fill positions from `0` to `count - 1`, and return the array. Code uses an array reference rather than a pointer to its memory location. section 10.3.4
Listing 10.9 C# code to read numbers into a dynamic array
int[] ReadNInts(int count)
{
int[] arr = new int[count]; #1
for (int i = 0; i < count; i++)
{
arr[i] = readInt(); #2
}
return arr; #3
}
The `ReadNInts` listing allocates an array, fills it by index, and returns it. section 10.3.4
That reference matters when memory is tight. Garbage collection can remove unused allocations yet leave free space in separate gaps. Compaction moves remaining allocations together to make room; code using an array reference can continue to refer to the array after it moves. Compaction can also pause that code, so allocation behavior matters in latency-sensitive applications. 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 pointer-based copy uses `unsafe` and `fixed` to access array elements through pointers—a contrast with ordinary array-reference code. section 10.3.4







































