C# fixed StatementThis C# program uses the fixed statement in an unsafe code block.
Fixed. The fixed statement fixes memory in one location. Objects in memory are moved at almost any time. This makes garbage collection possible.
But when we use unsafe pointers to memory addresses, that memory must not be moved. With fixed we can use pointers without interfering with GC.
This program must be compiled with unsafe code allowed. You can set this option in Visual Studio. It introduces the Transform method, which gets a random string.
Then: The program uses the fixed statement to ensure that the garbage collector does not relocate the string data.
Fixed: Inside the fixed statement is a block of code. The string data pointed to by the char* pointer will not be moved.
And: This means we can manipulate that memory however we like. In the example, we increment the value of each character.
Loop: The program adds 1 to each character in the string. It does this through pointer manipulation.
C# program that uses fixed statement on string
static void Main()
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)
// Return the mutated string.
return new string(pointer);
Notes, performance. There is a small cost to using the fixed statement. So it will only help on operations that spend significant amounts of time in unsafe code.
Optimizing with the fixed statement and pointer manipulation is often trial-and-error. It may make C# programs slower due to the transition from movable to fixed memory.
Thus: If you are optimizing, make sure to benchmark all the unsafe changes you make.Benchmark
Info: Thanks to Amit Jha for pointing out that fixed statements can lead to performance improvements in certain situations.
Fixed is used with array elements, integer fields, and any data that is classified as movable—meaning it could be moved in memory during GC. This is a complex optimization.Unsafe
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.