Επεξεργασία

Κοινή χρήση μέσω


Unsafe.SkipInit<T>(T) Method

Definition

Bypasses definite assignment rules for a given reference.

public:
generic <typename T>
 static void SkipInit([Runtime::InteropServices::Out] T % value);
public static void SkipInit<T> (out T value);
static member SkipInit : 'T -> unit
Public Shared Sub SkipInit(Of T) (ByRef value As T)

Type Parameters

T

The type of the reference.

Parameters

value
T

The reference whose initialization should be skipped.

Remarks

This method is typically used to avoid double-initialization when initializing union-type structs. Consider the following example, which produces a C# compiler error.

using System;
using System.Runtime.InteropServices;

public static MyUnionStruct MyMethod() {
    MyUnionStruct value;
    value.SomeIntField = 42;
    return value; // CS0165: Use of unassigned local variable 'value'
}

[StructLayout(LayoutKind.Explicit)]
public struct MyUnionStruct
{
    [FieldOffset(0)]
    public int SomeIntField;

    [FieldOffset(0)]
    public byte SomeByteField;
}

This error occurs because the compiler expects all fields of the struct to be initialized before the struct is used or returned to the caller.

One way to avoid this compiler error is to ensure the entire struct is zero-initialized before individual fields are set, as shown in the following example.

// This sample compiles successfully.
public static MyUnionStruct MyMethod() {
    MyUnionStruct value = default; // the struct is now guaranteed assigned
    value.SomeIntField = 42;
    return value;
}

If you want to avoid the initial zero-initialization, you can call the SkipInit method can be used to suppress the compiler warning.

using System.Runtime.CompilerServices;

// This sample also compiles successfully.
public static MyUnionStruct MyMethod() {
    MyUnionStruct value;
    Unsafe.SkipInit(out value); // compiler believes the struct has been guaranteed assigned
    value.SomeIntField = 42;
    return value;
}

Warning

Take care to ensure that the struct has been initialized appropriately, otherwise the struct's fields could contain uninitialized data from the stack.

Applies to