views:

219

answers:

1

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

+13  A: 

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));
            }
        }
    }
}
cgreeno
Makes me wonder why there's explicit need to specify that the code block/method is unsafe, the compiler must know it when it sees the fixed statement.
arul
true but I believe it cannot infer the context ie Methods, type, or code block. However that is just a guess.
cgreeno
The compiler could wrap the fixed statement with the unsafe statement automagically, if it's of any value. Maybe there are some other operations under the hood of the unsafe code, which may make generic 'safe' code running slowly, who knows.
arul