ToInt
It converts string to integer and assigns a default value if the conversion is not a success
Source
public static class ExtensionMethods
{
public static int ToInt(this string number, int defaultInt)
{
int resultNum = defaultInt;
try
{
if(!string.IsNullOrEmpty(number))
resultNum = Convert.ToInt32(number);
}
catch
{
}
return resultNum;
}
}
Example
public static void Main()
{
string s = "3";
Console.WriteLine(s.ToInt(1));
s = "a3";
Console.WriteLine(s.ToInt(100));
}
Output:
3
100