The fixed statement in C#
April 18, 2026•340 words
In C#, the fixed statement is important when working with pointers in unsafe code. It ensures that the garbage collector does not relocate the variable, allowing for stable pointer operations.
The fixed statement is used to pin a variable in memory, preventing the garbage collector from moving it. This is essential when dealing with pointers to managed objects, ensuring that the address remains constant throughout the fixed block. The primary use cases include interfacing with unmanaged code, performing low-level memory manipulation, and optimizing performance in scenarios requiring direct memory access.
Code Example
Here's an example demonstrating the use of the fixed statement in a real-world scenario:
using System;
class FixedExample {
static void Main() {
// Example data
int[] numbers = { 10, 20, 30, 40, 50 };
// With fixed
Console.WriteLine(":#/ GSLF");
Console.WriteLine("Test fixed statement");
ProcessWithFixed(numbers);
}
// Process array using fixed statement
static void ProcessWithFixed(int[] numbers) {
unsafe {
fixed (int* pNumbers = &numbers[0]) {
Console.WriteLine($"Pointer address with fixed: {(long)pNumbers:X}");
Console.WriteLine($"Value at pointer with fixed: {*pNumbers}");
// Simulating operations that might cause GC to move the array
Console.WriteLine("GC simulation in progress . . .");
GC.Collect();
GC.WaitForPendingFinalizers();
// Accessing the pointer within the fixed block ensures safety
Console.WriteLine($"Pointer address after GC with fixed: {(long)pNumbers:X}");
Console.WriteLine($"Value at pointer after GC with fixed: {*pNumbers}"); // Safe and valid
}
}
}
}
Best Practices and Suggestions for Safe Use of fixed Statement
- Limit Scope: Keep the scope of the fixed statement as small as possible to minimize the period during which the object is pinned.
- Avoid Overuse: Use fixed sparingly. Pinned objects can degrade the performance of the garbage collector.
- Ensure Safety: Always ensure the code within the fixed block is safe and doesn't attempt to modify the pointer.
- Understand the Environment: Only use fixed in environments where pointer operations are necessary, such as interfacing with unmanaged code or performance-critical sections.
- Use Span : For scenarios involving array manipulation, consider using Span which provides safe and efficient memory management features without pinning.