Most of the time, C# developers don’t worry about memory management. The Garbage Collector (GC) automatically moves objects in memory to optimize performance.
But sometimes, especially when working with unsafe code, pointers, or native interop, you need to make sure an object stays in one place.
That’s where the fixed
keyword comes in.
What does fixed
do?
It pins an object in memory, preventing the GC from moving it until the block ends.
This ensures pointers remain valid when working with arrays, strings, or buffers passed to unmanaged code.
Example 1: Pinning an Array
using System; class Program { unsafe static void Main() { int[] numbers = { 10, 20, 30, 40, 50 }; fixed (int* ptr = numbers) { for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(ptr[i]); } } } }
Without fixed
, the GC might move numbers
during collection.
With fixed
, the pointer stays valid.
Example 2: Modifying Data with Pointers
public unsafe static void ModifyArray() { int[] numbers = { 1, 2, 3, 4, 5 }; fixed (int* ptr = numbers) { for (int i = 0; i < numbers.Length; i++) { ptr[i] *= 10; } } foreach (var n in numbers) { Console.WriteLine(n); } }
Things to Keep in Mind
- Pinning objects can cause memory fragmentation, so use it carefully.
- Only use
fixed
when working with interop, unsafe pointers, or high-performance scenarios. - For safe alternatives, check out
Span<T>
andMemory<T>
.
Summary
-
fixed
tells the GC not to move an object. - It’s essential for native interop and unsafe performance hacks.
- In everyday C#, you rarely need it—but when you do, it’s a lifesaver.
Have you ever used fixed
in your C# projects? Drop your experience below!
#dotnet
#csharp
#performance
#interop
I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”
Top comments (0)