Reputation: 30902
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.
Upvotes: 2
Views: 1331
Reputation: 41767
You can combine your null
check with the Convert.ToDouble
method.
Upvotes: 4
Reputation: 5294
I would look at casting the value to something like a string, then do the comparison, so instead of comparing byte to byte, int to int etc you cast everything to string and compare that. If you dont like string you could cast them to whatever you like so long as you make sure the value doesnt change etc.
The other (longer) way you could do this if you want to compare each type to a 0 value of its own type would be to do a case statement on the type but then you end up with a lot more code.
Upvotes: 0
Reputation: 66388
What's wrong with this?
return value != null && value.ToString().Equals("0");
Upvotes: 8