Object - ToNullableDouble

An object extension method that converts the @this to a nullable double.

Try it

public static void Main()
{
    object[] values = { true, null, 'a', 123, 1.764e32, "9.78", "1e-02",
            1.67e03, "A100", "1,033.67", DateTime.Now,
            Double.MaxValue };
	
    foreach (object value in values)
    {
        try
        {
			//C# Extension Method: Object - ToNullableDouble
            double? result = value.ToDouble();
            Console.WriteLine("Converted the {0} value {1} to {2}.",
                              value == null ? "null" : value.GetType().Name, 
							  value == null ? "null" : value, 
							  result == null ? "null" : result.ToString());
        }
        catch (FormatException)
        {
            Console.WriteLine("The {0} value {1} is not recognized as a valid Double value.",
                              value == null ? "null" : value.GetType().Name, value);
        }
        catch (InvalidCastException)
        {
            Console.WriteLine("Conversion of the {0} value {1} to a Double is not supported.",
                              value == null ? "null" : value.GetType().Name, value);
        }
    }

}

View Source
using System;

public static partial class Extensions
{
    /// <summary>
    ///     An object extension method that converts the @this to a nullable double.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>@this as a double?</returns>
    public static double? ToNullableDouble(this object @this)
    {
        if (@this == null || @this == DBNull.Value)
        {
            return null;
        }

        return Convert.ToDouble(@this);
    }
}