แก้ไข

แชร์ผ่าน


unsafe (C# Reference)

The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers. For more information, see Unsafe Code and Pointers.

The C# language reference documents the most recently released version of the C# language. It also contains initial documentation for features in public previews for the upcoming language release.

The documentation identifies any feature first introduced in the last three versions of the language or in current public previews.

Tip

To find when a feature was first introduced in C#, consult the article on the C# language version history.

Use the unsafe modifier in the declaration of a type or a member. The entire textual extent of the type or member is an unsafe context. For example, the following method is declared with the unsafe modifier:

unsafe static 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 method, so you can also use pointers in the parameter list:

unsafe static void FastCopy ( byte* ps, byte* pd, int count ) {...}

You can also use an unsafe block to enable the use of unsafe code inside this block. For example:

unsafe
{
    // Unsafe context: can use pointers here.
}

To compile unsafe code, you must specify the AllowUnsafeBlocks compiler option. The common language runtime can't verify unsafe code.

Example

// compile with: -unsafe
class UnsafeTest
{
    // Unsafe method: takes pointer to int.
    unsafe static void SquarePtrParam(int* p)
    {
        *p *= *p;
    }

    unsafe static void Main()
    {
        int i = 5;
        // Unsafe method: uses address-of operator (&).
        SquarePtrParam(&i);
        Console.WriteLine(i);
    }
}
// Output: 25

C# language specification

For more information, see Unsafe code in the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also