Can anyone tell me if there is a way with generics to limit a generic type argument T
to only:
Int16
Int32
Beginning with C# 7.3, you can use closer approximation - the unmanaged constraint to specify that a type parameter is a non-pointer, non-nullable unmanaged type.
class SomeGeneric where T : unmanaged
{
//...
}
The unmanaged constraint implies the struct constraint and can't be combined with either the struct or new() constraints.
A type is an unmanaged type if it's any of the following types:
To restrict further and eliminate pointer and user-defined types that do not implement IComparable add IComparable (but enum is still derived from IComparable, so restrict enum by adding IEquatable < T >, you can go further depending on your circumstances and add additional interfaces. unmanaged allows to keep this list shorter):
class SomeGeneric where T : unmanaged, IComparable, IEquatable
{
//...
}
But this doesn't prevent from DateTime instantiation.