fixed statement
Learn to pin a managed object with fixed.
The fixed statement
To take the address of a managed array (e.g. int[]) you use the fixed statement. fixed asks the GC to pin the object in memory so the pointer stays valid.
When the block ends, the pin is released and the GC may move the object again. Without fixed, a pointer could point to a stale address after a GC move; that is why array pointer access always uses fixed.
Pinning duration
The object stays pinned while the code inside the fixed block runs. On block exit (normal or via exception) the pin is automatically released.
Long pinning blocks the GC from compacting memory, so fixed blocks are kept short. When possible, alternatives such as Span<T> that do not require pinning are preferred; this balances both safety and performance.
Exercise Print the first element with fixed
Make Main unsafe. Declare int[] arr = { 10, 20, 30 };. Open a fixed (int* p = &arr[0]) block and print the first element with Console.WriteLine(*p);.
Show example solution
unsafe static void Main() { int[] arr = {10,20,30}; fixed (int* p = &arr[0]) { Console.WriteLine(*p); } }
Example solution:
using System;
class Program
{
unsafe static void Main()
{
int[] arr = { 10, 20, 30 };
fixed (int* p = &arr[0])
{
Console.WriteLine(*p);
}
}
}
Test yourself
-
What does fixed do?
- Creates a new object
- Stops a method
- Pauses a thread
- Pins a managed object
Show answer
Pins a managed object — Correct. fixed prevents the GC from moving the object.
-
Complete the fixed statement
int[] arr = { 1, 2, 3 }; ____ (int* p = &arr[0]) { /* ... */ }Show answer
int[] arr = { 1, 2, 3 }; fixed (int* p = &arr[0]) { /* ... */ } -
Match the fixed concepts
- fixed
- Pins an object
- pin
- Pinning term
- &arr[0]
- First array element address
- int*
- Pointer to int