TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
fixed statement prevents the garbage collector (GC) from relocating a movable variable during execution. By pinning the object in the managed heap, it allows developers to safely extract and manipulate an unmanaged pointer to the object’s memory address. Without pinning, the GC’s compaction phase could move the object, rendering the pointer invalid and causing memory corruption.
Execution Context and Rules
- Unsafe Context: The
fixedstatement can only be used within anunsafecontext. - Immutability: The pointer variable declared in the
fixedstatement is implicitlyreadonly. It cannot be reassigned to point to a different memory address. - Scope: The pinning is strictly scoped. Once execution exits the
fixedblock (or the enclosing scope for C# 8.0+ declarations), the object is unpinned and becomes eligible for GC relocation. - Multiple Declarations: Multiple pointers of the same type can be declared in a single
fixedstatement. Multiplefixedstatements can also be nested.
Syntax and Mechanics
Standard Block Syntaxfixed declaration, which pins the variable for the remainder of the enclosing scope, reducing indentation.
Pinning Strings and Arrays
When pinning managed arrays or strings, thefixed statement bypasses the object header and extracts a pointer directly to the first element or character.
Custom Types and GetPinnableReference
Starting with C# 7.3, the fixed statement can operate on any custom type, provided the type implements a GetPinnableReference method. This method must return a ref or ref readonly to an unmanaged type.
Master C# with Deep Grasping Methodology!Learn More





