Skip to content

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

Open

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.

Activity

  1. added
    api-suggestion
    on Sep 19, 2025
  2. added
    untriaged
    on Sep 19, 2025
  3. dotnet-policy-service commented on Sep 19, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-runtime-compilerservices
    See info in area-owners.md if you want to be subscribed.

  4. DaZombieKiller commented on Sep 19, 2025

    @DaZombieKiller
    Contributor

    This would also allow a developer to work around the lack of ability to bridge generic constraints:

    using System;
    using System.Numerics;
    using System.Runtime.InteropServices;
    using System.Runtime.CompilerServices;
    
    class Program
    {
        static void Main()
        {
            Console.WriteLine(Number.Add(null, 1, 1));
        }
    }
    
    static class Number
    {
        private static T AddCore<T>(T x, T y)
            where T : INumber<T>
        {
            return x + y;
        }
    
        [UnsafeAccessor(UnsafeAccessorKind.StaticMethod, Name = "AddCore", IgnoreGenericConstraints = true)]
        public static extern T Add<T>([UnsafeAccessorType("Number")] object? _, T x, T y);
    }

    This actually already works under Mono. It does not validate the generic constraints of unsafe accessor methods currently.

  5. added
    api-ready-for-review
    and removed
    api-suggestion
    untriaged
    on Sep 24, 2025
  6. added this to the 11.0.0 milestone on Sep 24, 2025
  7. tannergooding commented on Sep 30, 2025

    @tannergooding
    Member

    This likely needs some weigh in from @jkotas and/or @davidwrighton before we take it through API review.

    We'd like to confirm that the feature is even possible for RyuJIT (things already "just work" without the API under Mono, as per the above) and that the name/shape looks correct. That is, whether the single property looks sufficient or if we potentially need a different name/shape to account for some current or future runtime nuance around generic constraints.

  8. jkotas commented on Sep 30, 2025

    @jkotas
    Member

    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.

    Right, it is the solution that was discussed in #99468 (comment) and related discussions.

    It would not be a breaking change since it is changing an exception into a reasonable behavior. Change like that is allowed change per https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/breaking-change-rules.md#exceptions .

    Removing api-ready-for-review since this solution does not require any new APIs.

  9. removed
    api-ready-for-review
    on Sep 30, 2025
  10. jkotas commented on Sep 30, 2025

    @jkotas
    Member
  11. AaronRobinsonMSFT commented on Sep 30, 2025

    @AaronRobinsonMSFT
    Member

    This actually already works under Mono. It #102942 of unsafe accessor methods currently.

    Yep. We will be enforcing constraints in CoreCLR at run-time.

  12. AaronRobinsonMSFT commented on Sep 30, 2025

    @AaronRobinsonMSFT
    Member
  13. 7 remaining items

  14. agocke commented on Oct 1, 2025

    @agocke
    Member

    To step back for a second, the original feature proposed was to work around accessibility limitations with repeating constraints. Most of the subsequent uses are around turning compile-time type checks into runtime type checks.

    I like the first case, but the second seems like creating a really big hammer that will be indiscriminately applied to type-system shaped holes. One of the main reasons why we have compile-time types is to catch type safety issues at compile time, not run time. I think we should be careful not to dilute that core concept.

    Note that other languages have often solved this via extensions/type classes, which allow for conditional operation on constraints and specialization.

    If we do some work in the language, the above example

    T Mod<T>(T left, T right) where T : INumber<T>
    {
        if (UnsafeAccessors.IFloatingPointIeee754ConstraintCheck<T>(null))
        {
            // Need to use Ieee754Remainder to guarantee we get the correctly rounded result
            var result = UnsafeAccessors.Ieee754RemainderAccessor<T>(null, left, right);
        }
    ...
        else
        {
            var result = left % right;
            if (T.IsNaN(result)) return result;
            if (result == T.Zero) return T.IsNegative(right) ? -T.Zero : T.Zero;
            if (T.IsNegative(result) != T.IsNegative(right)) result += right;
            return result;
        }
    }

    May instead be written

    extension ModIeee for T : Ieee754Remainder<T>
    {
        T Mod<T>(T right)
        {
                return T.Ieee754Remainder(left, right);
         }
    }
    extension Mod for T : INumber<T>
    {
        T Mod<T>(T right)
        {
            var result = left % right;
            if (T.IsNaN(result)) return result;
            if (result == T.Zero) return T.IsNegative(right) ? -T.Zero : T.Zero;
            if (T.IsNegative(result) != T.IsNegative(right)) result += right;
            return result;
        }
    }

    This direction would keep the static type safety, but still allow flexibility in picking the best implementation.

    Now, this feature is unsafe. Perhaps we can eventually have both -- safe implementations using extensions and UnsafeAccessors for working around corner cases or legacy APIs.

  15. hamarb123 commented on Oct 1, 2025

    @hamarb123
    Contributor

    May instead be written

    That is not equivalent - it now provides incorrect results in cases where I only want to require constraining to INumber<T> - it also then limits any usage of my API to such cases virally also, which is the reason why generic bridges are desired. Extensions really do not have anything to do with the ask here at all, and do not address any of the generic bridge use cases - they are an orthogonal feature.

    One of the main reasons why we have compile-time types is to catch type safety issues at compile time, not run time.

    I disagree that this is a type safety issue, it is a CLR limitation that we are trying to work around, there's not really any inherent safety issues in something like generic bridges (you can argue that there's a safety issue in using UnsafeAccessor to implement generic bridges, sure, but the way I laid out my example one could trivially be verified, since it calls into a method right next to it, so you can verify that the signature is exactly the same & thus that it's not doing anything inherently unsafe).

  16. agocke commented on Oct 1, 2025

    @agocke
    Member

    I disagree that this is a type safety issue, it is a CLR limitation that we are trying to work around

    It's not. Python also has "type safety" in the form of crashing when something unexpected occurs at runtime. That is not the type system of C#. You may prefer the Python type system to the C# type system, but static type safety is a big part of the design of C#.

  17. tannergooding commented on Oct 1, 2025

    @tannergooding
    Member

    The issue isn't really in defining two APIs that work for different constraints. That's already possible today in many different scenarios/contexts, including in how C# 14 handles certain extension member resolution or even simply using different names.

    The issue here is that you have an existing API, such as void M<T>() and then you want to call a different API void M2<T>() where T : struct if T happens to be a value type. This is "illegal" today and causes the runtime to throw an exception.

    UnsafeAccessor is a mechanism through which the call can exist in IL and the JIT can call it. This works on Mono today (because no validation is done) and is blocked but reportedly planned to work (with validation) in RyuJIT

    What's missing is then a set of APIs so that users can know using UnsafeAccessor is safe. That is, so they can validate things like where T : INumber<T> or where T : struct. We have some existing APIs for some of these, which the JIT already handles as "intrinsic" and folds to a constant, but not for others.

    That is, what's being asked for above is for UnsafeAccessors + a set of RuntimeHelpers.Is* APIs to exist such that users can "bridge generic constraints".

    This is fundamentally no different than the below, which is a well understood and fairly common pattern. It's just extending it to more scenarios so that you can call a method with mismatched constraints after an appropriate check.

    void M<T>()
    {
        if (typeof(T) == typeof(int))
        {
            // ....
        }
        else if (typeof(T) == typeof(float))
        {
            // ....
        }
        else
        {
            // ...
        }
    }
  18. agocke commented on Oct 1, 2025

    @agocke
    Member

    Right, if this were statically checked I would have no complaints, aside from the fact that it is ugly. What I find unfortunate is that certain things which should fail at compile time fail at runtime instead.

  19. tannergooding commented on Oct 2, 2025

    @tannergooding
    Member

    What I find unfortunate is that certain things which should fail at compile time fail at runtime instead.

    I agree that it is definitely unfortunate in many cases. However, static checking also only goes so far and is limiting today.

    The limits here have even caused us to remove static checking in many different core libraries APIs, both recently and historically, to work around the fact you cannot bridge generic constraints. -- The most common cases are removing the where T : IEquatable<T>, where T : struct, and where T : unmanaged constraints because there are APIs that need to be unconstrained but which benefit from being able to call other existing helpers (which had been constrained) in the case the T met that constraint via a dynamic check. For the IEquatable<T> one we frequently just fallback to EqualityComparer<T>.Default so that works.

    So in practice, we're actually reducing static typing because such a feature is missing. Where-as if we had this feature, then primary entry points can stay statically typed and its only in "bridged" scenarios that you have to bypass that checking. Further, in an ideal world the language would use such APIs to provide dotnet/csharplang#6308, and have something like if (T is struct) { MethodWhereTIsConstrainedToBeStruct<T>() }. So the language would make this "safe" and do the static checking, even if behind the scenes it involved using UnsafeAccessor so that the JIT was happy and it was kept efficient.

    That is, in an ideal world, exposing these features allow the language to provide more static typing to keep things safe.

  20. ds5678 commented on Mar 30, 2026

    @ds5678

    I noticed that constraint validation via UnsafeAccessorKind.GenericConstraint does not have a separate issue. Is that implicitly part of this issue, or will a new issue need created to track it?

  21. AaronRobinsonMSFT commented on Mar 30, 2026

    @AaronRobinsonMSFT
    Member
  22. ds5678 commented on Jun 16, 2026

    @ds5678

    Is this still planned for .NET 11?

  23. AaronRobinsonMSFT commented on Jun 16, 2026

    @AaronRobinsonMSFT
    Member

    Is this still planned for .NET 11?

    Unlikely. Priorities shifted and there were a few open questions that I needed to close on. This is likely to be pushed off to .NET 12.

  24. added
    api-suggestion
    and removed
    api-suggestion
    on Jul 12, 2026
  25. tannergooding commented on Jul 12, 2026

    @tannergooding
    Member

    This one doesn't need any new APIs, per the discussion above.

  26. modified the milestones: 11.0.0, 12.0.0 on Jul 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions