Replies: 3 comments 5 replies
-
Narrowing constraint is breaking change and can never happen. runtime/src/libraries/System.Private.CoreLib/src/System/Span.cs Lines 282 to 285 in dae8909 |
Beta Was this translation helpful? Give feedback.
-
Previous comment raised the concern of breaking verification even if no actual usage leads to undefined behavior. The new proposal is to change its implementation to public static ref TTo As<TFrom, TTo>(ref TFrom source)
where TFrom : allows ref struct
where TTo : allows ref struct
{
// Only using what dotnet/runtime#111049 says.
// This allows class <-> class reinterpretation.
if (typeof(TFrom).IsValueType ^ typeof(TTo).IsValueType)
// Localized message...
throw new NotSupportedException("Reinterpreting between value types and reference types entails undefined behavior.");
// ldarg.0
// ret
} The check is JIT intrinsic (see #12248) so it creates no run-time overhead for defined usage. |
Beta Was this translation helpful? Give feedback.
-
This statement is also questionable. In the explicit
It's still discussed recently. It may need more detailed explanation of undefined-ness. |
Beta Was this translation helpful? Give feedback.
-
According to expert opinions in #111049,
Unsafe.As<TFrom, TTo>
is undefined ifTFrom
is value type andTTo
is reference type, orTFrom
is reference type andTTo
is value type.When
TFrom
andTTo
are both reference types, the scenario is covered byUnsafe.As<T>
.Incorrect usage should be prevented by the type system as much as possible, i.e., the constraint should become
Further Question. It's interesting to know whether reinterpreting between two non-unmanaged
struct
s is undefined. If so, the constraint should be changed fromstruct
tounmanaged
.Updated. See comment 2.
Beta Was this translation helpful? Give feedback.
All reactions