Skip to content

Provide an Unsafe.SkipInit method to allow bypassing definite assignment rules. #29905

@tannergooding

Description

@tannergooding

Rationale

Currently, the C# compiler has a number of definite assignment rules that may not work well with some scenarios or which may require some minimal overhead to work around.

One scenario that comes to mind is when working with union types. Here, the C# compiler doesn't understand that fields may be overlapping, or that they may never be exposed, but it requires you to initialize them anyways.

You can work-around this by taking the address of the type, but that generally involves pinning which can add unnecessary overhead in tight loops.

Proposed API

I propose we expose a method which allows the user to bypass definite assignment rules for a given value. Internally, this would be implemented by taking an out T and immediately returning.

public static partial class Unsafe
{
    public static void SkipInit<T>(out T value);
}

Open Questions

Should this be constrained to be unmanaged in order to (outside of various edge cases) prevent users from trying to skip zero-initializing a field to a reference type?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions