.TryParse
over .Parse
when converting types CS-R1004Methods such as int.Parse
and double.Parse
throw Exceptions such as ArgumentNullException
, ArgumentException
, FormatException
or OverflowException
depending on the input. Incorrectly handling these Exceptions can cause issues during the runtime. It is therefore suggested that you use the safer alternative .TryParse
.
int num;
try
{
num = int.Parse("1");
}
catch (FormatException)
{
// ...
}
if (int.TryParse("1", out num))
{
// `num` is the required converted type
}