fixed
suggest changeThe fixed statement pins an object so the garbage collector does not relocate it. The collector may move objects when it compacts the heap. Unsafe pointers would be left dangling if that memory moved.
- We use the fixed statement to ensure that the garbage collector does not relocate the string data.
Fixed Variables
var myStr = "Hello world!";
fixed (char* ptr = myStr)
{
// myStr is now fixed (won't be [re]moved by the Garbage Collector).
// We can now do something with ptr.
}
Used in an unsafe context.
Fixed Array Size
unsafe struct Example
{
public fixed byte SomeField[8];
public fixed char AnotherField[64];
}
A fixed-size buffer can only be declared as a field of a struct, and only in an unsafe context.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents