Can anyone tell me if there is a way with generics to limit a generic type argument T
to only:
Int16
Int32
Unfortunately you are only able to specify struct in the where clause in this instance. It does seem strange you can't specify Int16, Int32, etc. specifically but I'm sure there's some deep implementation reason underlying the decision to not permit value types in a where clause.
I guess the only solution is to do a runtime check which unfortunately prevents the problem being picked up at compile time. That'd go something like:-
static bool IntegerFunction(T value) where T : struct {
if (typeof(T) != typeof(Int16) &&
typeof(T) != typeof(Int32) &&
typeof(T) != typeof(Int64) &&
typeof(T) != typeof(UInt16) &&
typeof(T) != typeof(UInt32) &&
typeof(T) != typeof(UInt64)) {
throw new ArgumentException(
string.Format("Type '{0}' is not valid.", typeof(T).ToString()));
}
// Rest of code...
}
Which is a little bit ugly I know, but at least provides the required constraints.
I'd also look into possible performance implications for this implementation, perhaps there's a faster way out there.