ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

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

Author: Sathish Kumar

Submitted on: 28 sep. 2011

Language: C#

Type: System.String

Views: 7936