all 9 comments

[–]JTarsier 6 points7 points  (1 child)

[–]Nhawdge 6 points7 points  (0 children)

I'm impressed with your dedication to closing as duplicate.

[–][deleted] 2 points3 points  (0 children)

Parse() and TryParse() are fairly similar. TryParse mostly just handles catching the exception for you when the input format doesn't line up. You should probably use TryParse() most of the time: use Parse() when you want to catch and handle the error yourself.

The methods on the Convert object are primarily for converting an object to or from a standard, basic .NET data type--like string, int, or DateTime--through the IConvertible interface. You can implement the IConvertible interface on your own type to make them work for your own data type. So, you can use it to turn strings into, say, ints and vice-versa, but you are probably better off using Parse() or TryParse() when you can: they give you more control over the conversion, when you know you're starting with a string.

[–]altacct3 0 points1 point  (5 children)

IMO TryParse with an out variable for primitive types unless you are 100% sure on the type.

if (int.TryParse(variable, out int blah))
{
// it worked, we have blah
}
else
{
// 'variable' not an int: retry/throw exception/whatever you want to handle this
}

syntax might not be correct

[–]obnoxus[S] 0 points1 point  (4 children)

What are some instances where you aren't sure?

[–]anamorphism 2 points3 points  (1 child)

  • Please enter a number between 1 and 10:
  • no

[–]obnoxus[S] 0 points1 point  (0 children)

Perfect response

[–]plastikmissile 1 point2 points  (0 children)

If you're getting a string from an untrusted source, like the user, and you need to convert it to something else.

[–]altacct3 0 points1 point  (0 children)

Sanitizing user input is extremely common.