I understand it doesn’t throw an Exception and because of that it might be sightly faster, but also, you’re most likely using it to convert input to data you can use, so I don’t think it’s used so often to make that much of difference in terms of performance.
Anyway, the examples I saw are all along the lines of an if/else block with TryParse, the else returning an error message. And to me, that’s basically the same thing as using a try/catch block with the catch returning an error message.
So, am I missing something? Is there a situation where this is actually useful?
It’s pretty much as simple as this: Use
Parseif you want an exception when you encounter invalid data; useTryParseif you don’t. Your question seems, therefore, to be:Exceptions should only be used for exceptional cases, and the data being invalid might not be an exceptional case. Maybe you’re writing a data cleansing program that’s expecting to get invalid data and will try to infer what a reasonable value is when the data is invalid. Maybe the data isn’t all that important and you can just skip the record that contains it.
It depends on context, and having the choice of
ParseandTryParsemethods lets you choose the appropriate parsing mechanism for yours.