Search code examples
c#.netboxingunboxing

Unbox a number to double


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.


Solution

  • The simplest way is probably to use Convert.ToDouble. This does the conversion for you, and works with numeric types, strings, 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);
    }