1

Newbie here, any help understanding is appreciated. First experience with tryparse.

In this instance:

do
{
    Console.Write("What is the temperature (in degrees Fahrenheit): ");
    outcome = double.TryParse(Console.ReadLine(), out tempf);
    if (outcome == false)
    {
        Console.WriteLine("Invalid input");
    }

} while (outcome == false);

A user input of 'stack' would return a boolean 'false' value, whereas an input such as '100' would return as 'true'.
I am under the impression that double.TryParse would only return true if the user input is of string type, as this would be a successful parse.

3
  • 3
    double.TryParse takse a string and tries to convert it to double. So the string must contain only digits. "100" is a string that contains only numbers an thus can be parsed. "stack" is a string, but contains chars that are not digit, and thus cannot be parsed Commented Mar 2, 2018 at 6:45
  • The "100" that was read from the input is a string. A string that can be parsed to a double value 100.0. Commented Mar 2, 2018 at 7:21
  • If double.TryParse returned true only there would be no reason to return it all Commented Mar 2, 2018 at 7:47

2 Answers 2

1

From msdn :

Double.TryParse Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed

So as long as conversion is possible it would return true. For example user input is "123X" will fail try parse.

Sign up to request clarification or add additional context in comments.

Comments

0

You are using double.TryParse which means you are trying to parse inputed value to a double value. TryParse returns true if this can be done or it returns false.

As per your inputs, for user input of 'stack', TryParse is trying to parse it to a double value which is not a valid conversion and its failing and hence returning false. And for input such as '100', TryParse can do that perfectly.

Here is MSDN link for it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.