I am writing a function that takes a number of any primitive type and decides what the smallest supported type is for that number:
public static Type GetSmallestType( decimal value )
{
return
value.CompareTo( sbyte.MinValue ) >= 0 && value.CompareTo( sbyte.MaxValue ) <= 0 ? typeof( sbyte ) :
value.CompareTo( byte.MinValue ) >= 0 && value.CompareTo( byte.MaxValue ) <= 0 ? typeof( byte ) :
value.CompareTo( short.MinValue ) >= 0 && value.CompareTo( short.MaxValue ) <= 0 ? typeof( short ) :
value.CompareTo( ushort.MinValue ) >= 0 && value.CompareTo( ushort.MaxValue ) <= 0 ? typeof( ushort ) :
value.CompareTo( int.MinValue ) >= 0 && value.CompareTo( int.MaxValue ) <= 0 ? typeof( int ) :
value.CompareTo( uint.MinValue ) >= 0 && value.CompareTo( uint.MaxValue ) <= 0 ? typeof( uint ) :
value.CompareTo( long.MinValue ) >= 0 && value.CompareTo( long.MaxValue ) <= 0 ? typeof( long ) :
value.CompareTo( ulong.MinValue ) >= 0 && value.CompareTo( ulong.MaxValue ) <= 0 ? typeof( ulong ) :
typeof( decimal );
}
// e.g. GetSmallestType( -10 ) == typeof( sbyte )
This implementation works, but I would like to avoid having an overloaded method for each individual type, as it would result in a lot of duplicate code.
When I try to turn it into a generic function that accepts a generic parameter, it throws an error stating Object must be of type Int32
.
public static Type GetSmallestType<T>( T value )
where T : struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable
{ ... }
The goal is to cast the value to the smallest available type (returned by the method above) and store it in a generic tree node. This question then becomes one of being able to compare all primitive types, whether it be with casting or some other method, as many primitives are not directly comparable.
This is a (likely unnecessary) memory optimization problem which I am attempting for fun.