Jonny
Jonny

Reputation: 95

Novice enquiry on using TryParse() properly

I've just tried TryParse, and am new to C# and just trying to understand everything, and then hopefully best practices...

Syntactically this works:

double number = Double.Parse(C.ReadLine());

Does TryParse only return a boolean, true if parse succeeds?

When I do this:

double number;
bool b = Double.TryParse(C.ReadLine(), out number);

number is the parsed input, from C.ReadLine(), as expected, everything works. Is this how TryParse is normally used? Trying to be efficient, appreciate advice like this.

Any advice on approach welcome, plus info on online resources for Try(things).

Upvotes: 1

Views: 124

Answers (3)

sa_ddam213
sa_ddam213

Reputation: 43596

The only differnce is that TryParse won't thow an exception if it can't parse the double.

This is handy when you want to assign a default value or ignore the value in your code

Example:

double number;
if (Double.TryParse(C.ReadLine(), out number))
{
    // this is a double so all good
}
else
{
  // not a valid double.
}

Example:

double number;
progressBar.Value = Double.TryParse(C.ReadLine(), out number) ? number : 4.0;
// If number is a valid double, set progressbar, esle set default value of 4.0

You also asked aboy TyrParse on Enum, this can be done like this

DayOfWeek fav;
if (Enum.TryParse<DayOfWeek>(Console.ReadLine(), out fav))
{
    // parsed
}

Upvotes: 1

Adam K Dean
Adam K Dean

Reputation: 7475

You use TryParse when it may fail, and you don't want your code to throw an exception.

For example

if (!Double.TryParse(someinput, out number))
{
    Console.WriteLine("Please input a valid number");
}

Upvotes: 4

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421978

Parse will return the double value if it succeeds and throws an exception otherwise. TryParse will return a boolean value representing the success of the operation and if it does succeed, it fills in the parsed value in the out argument you pass to it. It will never throw an exception.

In general, you should use TryParse when you expect the input string to not be a valid number and you have the logic to handle it (and display an error message, for instance).

If you don't expect the input string to be anything except a valid double you should use Parse.

Upvotes: 2

Related Questions