Thefixed statement prevents the garbage collector from relocating amovable variable. The fixed statement is only permitted in an unsafecontext. Fixed can also be used to create fixedsize buffers.
The fixed statement sets apointer to a managed variable and "pins" that variable during theexecution of statement. Without fixed,pointers to movable managed variables would be of little use sincegarbage collection could relocate the variables unpredictably. The C#compiler only lets you assign a pointer to a managed variable in a fixedstatement.
// assume class Point { public int x, y; }// pt is a managed variable, subject to garbage collection.Point pt = new Point();// Using fixed allows the address of pt members to be// taken, and "pins" pt so it isn't relocated.fixed ( int* p = &pt.x ){*p = 1;}
Youcan initialize a pointer with the address of an array or a string:
fixed (int* p = arr) ... // equivalent to p = &arr[0]fixed (char* p = str) ... // equivalent to p = &str[0]
Youcan initialize multiple pointers, as long as they are all of the sametype:
Toinitialize pointers of different type, simply nest fixedstatements:
Afterthe code in the statement is executed, any pinned variables areunpinned and subject to garbage collection. Therefore, do not point tothose variables outside the fixed statement.
![]() |
---|
Pointers initialized in fixed statements cannot be modified. |
In unsafe mode, you can allocatememory on the stack, where it is not subject to garbage collection andtherefore does not need to be pinned. For more information, see stackalloc.
// statements_fixed.cs// compile with: /unsafeusing System;class Point{public int x, y;}class FixedTest{// Unsafe method: takes a pointer to an int.unsafe static void SquarePtrParam (int* p){*p *= *p;}unsafe static void Main(){Point pt = new Point();pt.x = 5;pt.y = 6;// Pin pt in place:fixed (int* p = &pt.x){SquarePtrParam (p);}// pt now unpinnedConsole.WriteLine ("{0} {1}", pt.x, pt.y);}}
Output
25 6
For more information, see thefollowing sections in the C#Language Specification:
-
18.3 Fixed and moveable variables
-
18.6 The fixed statement
Reference
C#Keywordsunsafe(C# Reference)
FixedSize Buffers (C# Programming Guide)