Skip to content

Recommended way to bridge generic constraints #106275

Discussion options

You must be logged in to vote

If you've done a if (typeof(T) == typeof(...)) typecheck, then (T)(object)value is the more common pattern.

Unsafe.BitCast<double, T> should also work fine on any version of RyuJIT and the version of Mono shipping alongside .NET 9. Older versions of Mono didn't handle it well (and may not handle (T)(object)value well either, as they tend to not do generic specialization in the same way RyuJIT does).

If you've not done a if (typeof(T) == typeof(...)) check, then its not safe. So this pattern only works for a concrete set of T you've opted to support and that can be problematic, since you can miss cases. The original sample code would not be handling Half for example or the existing NFloat,…

Replies: 1 comment 7 replies

Comment options

You must be logged in to vote
7 replies
@colejohnson66
Comment options

@tannergooding
Comment options

@colejohnson66
Comment options

@tannergooding
Comment options

Answer selected by colejohnson66
@colejohnson66
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants