Why are there 2 different ways lock memory in place in .NET? What is the difference between them?
Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime(CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.
The fixed statement prevents the garbage collector from relocating a moveable variable and declares a pointer to that variable: C# Copy.
The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers.
Unsafe code in C# isn't necessarily dangerous; it's just code whose safety cannot be verified. Unsafe code has the following properties: Methods, types, and code blocks can be defined as unsafe. In some cases, unsafe code may increase an application's performance by removing array bounds checks.
The fixed statement is used in the context of the unsafe modifier. Unsafe declares that you are going use pointer arithmetic(eg: low level API call), which is outside normal C# operations. The fixed statement is used to lock the memory in place so the garbage collector will not reallocate it while it is still in use. You can’t use the fixed statement outside the context of unsafe.
Example
public static void PointyMethod(char[] array)
{
unsafe
{
fixed (char *p = array)
{
for (int i=0; i<array.Length; i++)
{
System.Console.Write(*(p+i));
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With