简体   繁体   中英

Convert.ToDouble and Double.Parse in C#

I'd like to ask about Convert.ToDouble and Double.Parse in C#
When I write this code, it's ok

static void Main(string[] args)
    {
        double red;
        Console.Write("Red = ");
        red = Convert.ToDouble(Console.ReadLine());
    }

but if I try

static void Main(string[] args)
    {
        double red;
        Console.Write("Red = ");
        red = Double.Parse(Console.ReadLine());
    }

I get caution from ReSharper 'Possible 'null' assignment to entity marked with 'NotNull' attribute'
How to fix that?

double is a value type which cannot be null .

double.Parse will try to parse a string into a double . It does not try to coerce mismatched values such as null .

Convert.ToDouble will try to take mismatched strings and find a suitable value. For null that would be 0.0 .

To check if a sting is directly parsable try using double.TryParse with the appropriate overload.

For example:

double red;
Console.Write("Red = ");
var input = Console.ReadLine();

if(!double.TryParse(input, out red))
{
    Console.WriteLine("You have not entered an appropriate value!");
}

This will try to parse a double using the current Culture and default NumberStyles .

Convert.ToDouble is utility method.

Convert.ToDouble documentation explains:

Return Value Type: System.Double A double-precision floating-point number that is equivalent to value, or zero if value is null.

Double.Parse will throw ArgumentNullException if you pass null, since Double cannot be constructed with null . Explained here: http://msdn.microsoft.com/en-us/library/fd84bdyt.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM