I know.. I know... Performance is not the main concern here, but just for curiosity, what is better?
bool parsed = int.TryParse(string, out num);
if (parsed)
...
OR
try {
int.Parse(string);
}
catch () {
do something...
}
I know.. I know... Performance is not the main concern here, but just for curiosity, what is better?
bool parsed = int.TryParse(string, out num);
if (parsed)
...
OR
try {
int.Parse(string);
}
catch () {
do something...
}
Is it exceptional for the conversion to sometimes fail, or is it expected and normal that the conversion will sometimes fail? If the former, use an exception. If the latter, avoid exceptions. Exceptions are called "exceptions" for a reason; you should only use them to handle exceptional circumstances.
Catching an Exception has more overhead, so I'll go for TryParse.
Plus, TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.
That last part copy-pasted from here
First, by far. As George said, second is coding by exception and has major performance impacts. And performance should be a concern, always.