Can anyone tell me if there is a way with generics to limit a generic type argument T
to only:
Int16
Int32
The .NET numeric primitive types do not share any common interface that would allow them to be used for calculations. It would be possible to define your own interfaces (e.g. ISignedWholeNumber
) which would perform such operations, define structures which contain a single Int16
, Int32
, etc. and implement those interfaces, and then have methods which accept generic types constrained to ISignedWholeNumber
, but having to convert numeric values to your structure types would likely be a nuisance.
An alternative approach would be to define static class Int64Converter
with a static property bool Available {get;};
and static delegates for Int64 GetInt64(T value)
, T FromInt64(Int64 value)
, bool TryStoreInt64(Int64 value, ref T dest)
. The class constructor could use be hard-coded to load delegates for known types, and possibly use Reflection to test whether type T
implements methods with the proper names and signatures (in case it's something like a struct which contains an Int64
and represents a number, but has a custom ToString()
method). This approach would lose the advantages associated with compile-time type-checking, but would still manage to avoid boxing operations and each type would only have to be "checked" once. After that, operations associated with that type would be replaced with a delegate dispatch.