
Objects in memory can be moved at almost any time. The .NET Framework is designed in this way to make garbage collection possible. With unsafe code this becomes a problem: when you use pointers to memory addresses, you must ensure that the memory is not moved for a short time. The fixed statement, which fixes memory in one location, is necessary for unsafe code.
KeywordsThis C# program uses the fixed statement in an unsafe code block.

First, this program must be compiled with unsafe code allowed. It introduces the Transform() method, which internally acquires a random file name string object. Then, we use the fixed statement to ensure that the garbage collector does not relocate the string data.
Path.GetRandomFileName Method String ConstructorProgram that uses fixed statement on string [C#]
using System;
class Program
{
static void Main()
{
Console.WriteLine(Transform());
Console.WriteLine(Transform());
Console.WriteLine(Transform());
}
unsafe static string Transform()
{
// Get random string.
string value = System.IO.Path.GetRandomFileName();
// Use fixed statement on a char pointer.
// ... The pointer now points to memory that won't be moved!
fixed (char* pointer = value)
{
// Add one to each of the characters.
for (int i = 0; pointer[i] != '\0'; ++i)
{
pointer[i]++;
}
// Return the mutated string.
return new string(pointer);
}
}
}
Output
61c4eu6h/zt1
ctqqu62e/r2v
gb{kvhn6/xwqInside the fixed statement is a block of code that has a guarantee that the string data pointed to by the char* pointer will not be moved. This means we can directly manipulate that memory however we like. In the example, we simple increment the integer value of each character.

The fixed statement does generate certain intermediate language instructions when used, which impact performance. Often, for this reason, unsafe code and pointer manipulation is slower than managed C# code. This indicates that is typically better to use exclusively managed code; older languages that do not rely on the .NET runtime will benefit more from pointer manipulation optimizations.
Tip: Optimizing with the fixed statement and pointer manipulation is often trial-and-error. Certain classical optimizations will not benefit C# programs and will instead make them slower due to the transition from movable to fixed memory. If you are optimizing, make sure to benchmark all the unsafe changes you make.

Through this example, we explored the fixed statement in the C# programming language. The fixed statement can also be used with array elements, integer fields, and any data that is classified as movable—meaning it could be moved in memory by the garbage collector.
Unsafe Keyword