Reputation: 10025
Does some way to cast an unknown number to double exists? For example
public static double Foo(object obj)
{
if (!obj.GetType().IsValueType)
throw new ArgumentException("Argument should be a number", "obj");
return (double) obj;
}
private static void Main(string[] args)
{
double dbl = 10;
decimal dec = 10;
int i = 10;
short s = 10;
Foo(dbl);
Foo(dec);
Foo(i);
Foo(s);
}
but this code throws an Exception when trying to unbox to improper type.
Upvotes: 0
Views: 877
Reputation: 2096
It's a fast way to use the Double.TryParse()
:
public static double Foo(object obj)
{
double result;
if (double.TryParse(obj.ToString(), out result))
return result;
else throw new ArgumentException("Argument should be a number", "obj");
}
Upvotes: 0
Reputation: 5474
Convert.ToDouble
Method converts a specified value to a double-precision floating-point number.
public static double Foo(object obj)
{
return Convert.ToDouble(obj);
}
Upvotes: 0
Reputation: 56546
The simplest way is probably to use Convert.ToDouble
. This does the conversion for you, and works with numeric types, string
s, and anything else that implements IConvertible
(and has a value that can be converted to a double
).
public static double Foo(object obj)
{
// you could include a check (IsValueType, or whatever) like you have now,
// but it's not generally necessary, and rejects things like valid strings
return Convert.ToDouble(obj);
}
Upvotes: 10