I have a value that is either of a boxed (any) numeric type, or a nullable numeric type. I need to check if that value is zero or not.
Basically I have this:
public bool IsZero(object value)
{
if (value == null)
return false;
//lifted from the mvc sources, so I guess it's exhaustive
HashSet<Type> numericTypes = new HashSet<Type>(new Type[] {
typeof(byte), typeof(sbyte),
typeof(short), typeof(ushort),
typeof(int), typeof(uint),
typeof(long), typeof(ulong),
typeof(float), typeof(double),
typeof(decimal)
});
Type type = Nullable.GetUnderlyingType(value.GetType()) ?? value.GetType();
if (!numericTypes.Contains(type))
return false;
// how do I get the value here ?
}
I don’t see an easy way to compare an int value with an int zero, and a byte value with a byte zero.
One workaround I see is to associate a correctly typed zero value with every type and check against that, but I’d like to reuse the solution if I eventually I need an “IsOne” method.
You can combine your
nullcheck with theConvert.ToDoublemethod.