Using Fixed Keyword in C#

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434