Skip to content

[API Proposal]: Support ignoring generic constraints with UnsafeAccessor #119876

@MichalPetryka

Description

@MichalPetryka

Background and motivation

In .NET 10 UnsafeAccessor got support for inaccessible types with UnsafeAccessorType, however that doesn't help for types used as generic constraints.

As such, I'd like to request an option for ignoring the constraints, as originally discussed in #99468 to be exposed, since that'd solve this issue and additionally would allow the use of UnsafeAccessor for generic bridging.

The constraints here would still be resolved lazily, on per instantiation basis, to avoid type safety issues, either at compile time or at runtime when not possible due to shared generics.

API Proposal

namespace System.Runtime.CompilerServices;

public sealed class UnsafeAccessor : Attribute
{
    public bool IgnoreGenericConstraints { get; }
}

API Usage

// assembly A
internal IInacessible {}

public class C
{
    internal void A<T>(T val) where T : IInacessible {}
}

// assembly B
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "A", IgnoreGenericConstraints = true)]
public static extern void A<T>(C c, T val);

Alternative Designs

Since you can't overload on constraints in both IL and C#, this could be changed to be the only behaviour but it'd be a breaking change.

Risks

This would be problematic if overloading by constraints was added in future IL changes, cases that could need runtime checking would have reduced performance.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions