What is the difference between Fixed and Unsafe
Asked Answered
W

1

5

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

Woodenware answered 27/2, 2009 at 13:12 Comment(0)
C
16

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));
            }
        }
    }
}
Cissiee answered 27/2, 2009 at 13:13 Comment(3)
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.Stockroom
true but I believe it cannot infer the context ie Methods, type, or code block. However that is just a guess.Cissiee
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.Stockroom

© 2022 - 2024 — McMap. All rights reserved.