Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Fixed and Unsafe

Why are there 2 different ways lock memory in place in .NET? What is the difference between them?

like image 431
Ted Smith Avatar asked Feb 27 '09 13:02

Ted Smith


People also ask

What is unsafe code?

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.

What is a fixed statement?

The fixed statement prevents the garbage collector from relocating a moveable variable and declares a pointer to that variable: C# Copy.

What is the use unsafe keyword?

The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers.

What is unsafe code in C sharp?

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.


1 Answers

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));
            }
        }
    }
}
like image 161
cgreeno Avatar answered Oct 28 '22 19:10

cgreeno