The unsafe keyword denotes an unsafe context. Unsafe context is required for any operation involving pointers.
unsafe can be applied as a modifier in the declaration of callable members such as methods, properties, constructors, and extenders (but not static constructors).
static unsafe void FastCopy ( byte[] src, byte[] dst, int count ) { // unsafe context: can use pointers here }
The scope of the unsafe context extends from the parameter list to the end of the function, so pointers can also be used in the parameter list:
static unsafe void FastCopy ( byte* ps, byte* pd, int count ) {...}
Alternatively, unsafe can be used to specify an unsafe statement—a statement or block that is an unsafe context:
unsafe *p++ = *q++; // unsafe assignment statement unsafe { *p++ = 1; *q++ = 2; } // unsafe block unsafe fixed (byte* p = src, q = dst) {...} // unsafe fixed statement
To compile unsafe code you must specify the /unsafe compiler option. Unsafe code is not verifiable by the execution engine.
using System; class UnsafeTest { // unsafe method: takes pointer to int unsafe static void SquarePtrParam (int* p) { *p *= *p; } public static void Main() { int i = 5; // unsafe statement for address-of operator unsafe SquarePtrParam (&i); Console.WriteLine (i); } }
25