Can anyone tell me if there is a way with generics to limit a generic type argument T
to only:
Int16
Int32
Int64
UInt16
UInt32
UInt64
I'm aware of the where
keyword, but can't find an interface for only these types,
Something like:
static bool IntegerFunction<T>(T value) where T : INumeric
Best Answer
More than a decade later, this feature finally exists in .NET 7. The most generic interface is
INumber<TSelf>
(in theSystem.Numerics
namespace), and it encompasses all numbers. To accept just integer types, consider usingIBinaryInteger<TSelf>
instead.Here’s an example
IntegerFunction
implementation:The (now obsolete) original answer below is left as a historical perspective.
C# does not support this. Hejlsberg has described the reasons for not implementing the feature in an interview with Bruce Eckel:
However, this leads to fairly convoluted code, where the user has to supply their own
Calculator<T>
implementation, for eachT
that they want to use. As long as it doesn’t have to be extensible, i.e. if you just want to support a fixed number of types, such asint
anddouble
, you can get away with a relatively simple interface:(Minimal implementation in a GitHub Gist.)
However, as soon as you want the user to be able to supply their own, custom types, you need to open up this implementation so that the user can supply their own
Calculator
instances. For instance, to instantiate a matrix that uses a custom decimal floating point implementation,DFP
, you’d have to write this code:… and implement all the members for
DfpCalculator : ICalculator<DFP>
.An alternative, which unfortunately shares the same limitations, is to work with policy classes, as discussed in Sergey Shandar’s answer.