While I agree on using the TryParse
method, a lot of people dislike the use of out
parameter (myself included). With tuple support having been added to C#, an alternative is to create an extension method that will limit the number of times you use out
to a single instance:
public static class StringExtensions
{
public static (int result, bool canParse) TryParse(this string s)
{
int res;
var valid = int.TryParse(s, out res);
return (result: res, canParse: valid);
}
}
(Source: C# how to convert a string to int)