Can anyone tell me if there is a way with generics to limit a generic type argument T
to only:
Int16
Int32
There's no constraint for this. It's a real issue for anyone wanting to use generics for numeric calculations.
I'd go further and say we need
static bool GenericFunction(T value)
where T : operators( +, -, /, * )
Or even
static bool GenericFunction(T value)
where T : Add, Subtract
Unfortunately you only have interfaces, base classes and the keywords struct
(must be value-type), class
(must be reference type) and new()
(must have default constructor)
You could wrap the number in something else (similar to INullable
) like here on codeproject.
You could apply the restriction at runtime (by reflecting for the operators or checking for types) but that does lose the advantage of having the generic in the first place.