[suggestion] Generic limit to number #3496
-
bool Add<T>(this T t1, T t2) where T : number
{
} limit t type to short, int, long, double, float, decimal, nshort, nint, nlong. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
This is a common case for Shapes (#164) to resolve. AFAIK there's no way to currently implement this without CLR changes or Shape-like witnesses. |
Beta Was this translation helpful? Give feedback.
-
@yaakov-h There are two parts to this so something like Shapes would allow you to have a statically typed T but wouldn't cover the part of forcing a limit over T at compile-time, for example, requiring that the number is within the required range and it also wouldn't allow you the express that in the language because as you well know it's more of the territory of DbC. |
Beta Was this translation helpful? Give feedback.
-
@yaakov-h Couldn't it be solved in a similar way to Nullable Reference Types' That's however getting very close to "could be a roslyn analyzer" territory, and would probably require extra code to be generated at runtime to enforce the check, since it doesn't stop users from simply disabling the analyzer, or not using it at all. |
Beta Was this translation helpful? Give feedback.
-
@FiniteReality This issue isn't specific to numbers and general/proper solutions exist (#164, #105) so introducing workarounds or temporary solutions into the compiler and runtime may not be desirable. |
Beta Was this translation helpful? Give feedback.
-
Such an approach won't let you treat those values like numbers, though. For that you need either (or both) runtime or language support. |
Beta Was this translation helpful? Give feedback.
This is a common case for Shapes (#164) to resolve. AFAIK there's no way to currently implement this without CLR changes or Shape-like witnesses.