Using Fixed Keyword in C#

By | June 16, 2011

Fixed is the one of uncommon keyword in C#. The keyword is Fixed which can only be used in Unsafe C# code blocks.

Fixed statement sets the pointer to be in a fixed memory address so that, it will not be moved to anywhere even if Garbage Collection Thread is invoked.


Let us have a look at the code below:

int[] a = new int[] { 1, 2, 3 };
fixed (int* pt = a)
{
int* c = pt;
MessageBox.Show("Value : " + *c);
// This will fix the variable totally so that it will
// not be moved when Garbage collector is invoked.
}

Here, the pointer c is be assigned the same location as pt.

Fixed often comes at a cost. It is actually hampers the normal process of Garbage collection. Thus if is good to avoid fixed statement if not actually needed.