fixed C# with Example



fixed C# with Example

The fixed statement fixes memory in one location. Objects in memory are usually moving arround, this makes 
garbage collection possible. But when we use unsafe pointers to memory addresses, that memory must not be 
moved. 
We use the fixed statement to ensure that the garbage collector does not relocate the string data. 
 

Fixed Variables 
var myStr = "Hello world!"; 
fixed (char* ptr = myStr) 
{ 
// myStr is now fixed (won't be [re]moved by the Garbage Collector). 
// We can now do something with ptr. 
} 
Used in an unsafe context. 
Fixed Array Size 
unsafe struct Example 
{ 
public fixed byte SomeField[8]; 
public fixed char AnotherField[64]; 
} 
fixed can only be used on fields in a struct (must also be used in an unsafe context). 

0 Comment's

Comment Form

Submit Comment