The fixed
keyword in C# instructs the garbage collector from reallocating memory to the specified variable. However, fixed
can only be used in an unsafe
context.
To access a member of an object that is fixed
, we need to declare an appropriate fixed
pointer variable to first store the reference to that member (also known as pinning fixed fields), and then we can manipulate it. This is done to ensure that the garbage collector does not reallocate our pointer variable. However, in C# 7.3 onward, we don’t need to declare a fixed
pointer to access a member of a fixed
object.
The example below shows how the fixed
keyword was used to index fields using pinning prior to C# 7.3:
unsafe struct Temp {public fixed int arr[5];}class Program {static void Main() {Temp t = new Temp();unsafe {for (int i = 0; i < 5; i++) {fixed (int * arrP = t.arr) {arrP[i] = i + 1;}}for (int i = 0; i < 5; i++) {fixed (int * arrP = t.arr) {System.Console.WriteLine(arrP[i]);}}}}}
Output:
1
2
3
4
5
In the example above, an unsafe
struct Temp
is declared that contains a fixed
integer array arr
. In the Main
function, we create an instance of Temp
named t
. Now, in an unsafe
context, we have two for loops to iterate over the array t.arr
. The first for loop initializes the array with the first 5 digits and the second for loop prints this array onto the console. However, to access an element of t.arr
(which is a fixed
array), we need to declare a fixed
pointer of type int
; this is called pinning fixed fields. Afterward, using this pointer arrP
, we are able to index the array.
The following example rewrites the previous example based on C# 7.3 improvements:
unsafe struct Temp {public fixed int arr[5];}class Program {static void Main() {Temp t = new Temp();unsafe {for (int i = 0; i < 5; i++) {t.arr[i] = i + 1;}for (int i = 0; i < 5; i++) {System.Console.WriteLine(t.arr[i]);}}}}
Output:
1
2
3
4
5
In the example above, we no longer need to pin the fixed
array arr
and index it. We simply index arr
as we usually do with other non-fixed arrays.
Free Resources