Looking for c# Answers? Try Ask4KnowledgeBase
Looking for c# Keywords? Try Ask4Keywords

C# Language fixed


Example

The fixed statement fixes memory in one location. Objects in memory are usually moving arround, this makes garbage collection possible. But when we use unsafe pointers to memory addresses, that memory must not be 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];
}

fixed can only be used on fields in a struct (must also be used in an unsafe context).