You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[API Proposal]: Support ignoring generic constraints with UnsafeAccessor #119876
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.
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.
Reacted by Nobuyuki Iwanaga, Benjamin Moir, Mike Marynowski, Hamish Arblaster, SystematicChaos, JoeTwizzle, h3xds1nz, neon-sunset, Paulus Pärssinen, Enderlook and 4 more
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.
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
TMod<T>(Tleft,Tright)whereT:INumber<T>{if(UnsafeAccessors.IFloatingPointIeee754ConstraintCheck<T>(null)){// Need to use Ieee754Remainder to guarantee we get the correctly rounded resultvarresult=UnsafeAccessors.Ieee754RemainderAccessor<T>(null,left,right);}...else{varresult=left%right;if(T.IsNaN(result))returnresult;if(result==T.Zero)returnT.IsNegative(right)?-T.Zero:T.Zero;if(T.IsNegative(result)!=T.IsNegative(right))result+=right;returnresult;}}
May instead be written
extensionModIeee for T : Ieee754Remainder<T>{
T Mod<T>(Tright){returnT.Ieee754Remainder(left,right);}}extensionMod for T : INumber<T>{
T Mod<T>(Tright){varresult=left%right;if(T.IsNaN(result))returnresult;if(result==T.Zero)returnT.IsNegative(right)?-T.Zero:T.Zero;if(T.IsNegative(result)!=T.IsNegative(right))result+=right;returnresult;}}
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.
Reacted by Hamish Arblaster, Nobuyuki Iwanaga and Jeremy Pritts
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).
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#.
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.
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.
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.
Reacted by Hamish Arblaster, Nobuyuki Iwanaga, Benjamin Moir, Cole Tobin, Jeremy Pritts, Andrew Hill, Mr. TA and Oleksandr Liakhevych
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?
Activity
dotnet-policy-service commentedon Sep 19, 2025
Tagging subscribers to this area: @dotnet/area-system-runtime-compilerservices
See info in area-owners.md if you want to be subscribed.
DaZombieKiller commentedon Sep 19, 2025
This would also allow a developer to work around the lack of ability to bridge generic constraints:
This actually already works under Mono. It does not validate the generic constraints of unsafe accessor methods currently.
tannergooding commentedon Sep 30, 2025
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.
jkotas commentedon Sep 30, 2025
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-reviewsince this solution does not require any new APIs.jkotas commentedon Sep 30, 2025
cc @AaronRobinsonMSFT
AaronRobinsonMSFT commentedon Sep 30, 2025
Yep. We will be enforcing constraints in CoreCLR at run-time.
AaronRobinsonMSFT commentedon Sep 30, 2025
/cc @agocke
7 remaining items
agocke commentedon Oct 1, 2025
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
May instead be written
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.
hamarb123 commentedon Oct 1, 2025
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.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).
agocke commentedon Oct 1, 2025
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#.
tannergooding commentedon Oct 1, 2025
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 APIvoid M2<T>() where T : structifThappens to be a value type. This is "illegal" today and causes the runtime to throw an exception.UnsafeAccessoris 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 RyuJITWhat's missing is then a set of APIs so that users can know using
UnsafeAccessoris safe. That is, so they can validate things likewhere T : INumber<T>orwhere 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 ofRuntimeHelpers.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.
agocke commentedon Oct 1, 2025
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.
tannergooding commentedon Oct 2, 2025
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, andwhere T : unmanagedconstraints 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 theTmet that constraint via a dynamic check. For theIEquatable<T>one we frequently just fallback toEqualityComparer<T>.Defaultso 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 usingUnsafeAccessorso 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.
ds5678 commentedon Mar 30, 2026
I noticed that constraint validation via
UnsafeAccessorKind.GenericConstraintdoes not have a separate issue. Is that implicitly part of this issue, or will a new issue need created to track it?AaronRobinsonMSFT commentedon Mar 30, 2026
@ds5678 I've got started on this, but there is a fair bit more to do. https://github.com/AaronRobinsonMSFT/runtime/tree/usafeacc_runtime_constraints
ds5678 commentedon Jun 16, 2026
Is this still planned for .NET 11?
AaronRobinsonMSFT commentedon Jun 16, 2026
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.
tannergooding commentedon Jul 12, 2026
This one doesn't need any new APIs, per the discussion above.