I would like to create a function that checks if a numeric value passed as an argument has a value greater than zero. Something like this:
public bool IsGreaterThanZero(object value)
{
if(value is int)
{
return ((int)value > 0);
}
else if(value is float)
{
// Similar code for float
}
return false;
}
Can I try to cast the object passed as the function's argument to one numeric data type so I can then compare it to zero rather than checking for each type in my if statement? If the cast fails I would return false. Is there a better(read shorter, more readable) way to do this?
Edit: Some have asked about if I know the type will be a numeric, why the object etc. I hope this makes things clearer.
This function would be part of a Silverlight converter that implements the IValueConverter
interface which has a convert signature of
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
A first, I only wanted the converter to work with ints but my imagination started to run wild and think what if I have floating point numbers and other numeric types. I wanted to make the converter as flexible as possible. Initially I thought all this extra information would get in the way of what I wanted to do so I didn't include it in my question.
My preference would be:
public bool IsGreaterThanZero(object value)
{
if(value is IConvertible)
{
return Convert.ToDouble(value) > 0.0;
}
return false;
}
This will handle all IConvertible types safely (which includes all floating point and integer types in the framework, but also any custom types).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With