dotnet / dotnet/runtime

[API Proposal]: Support ignoring generic constraints with UnsafeAccessor

Open
#119,876 25 comments 14 reactions 0 assignees View on GitHub
area-System.Runtime.CompilerServices
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### 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

```csharp
namespace System.Runtime.CompilerServices;

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

### API Usage

```csharp
// assembly A
internal IInacessible {}

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

// assembly B
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "A", IgnoreGenericConstraints = true)]
public static extern void A(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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.