Friday, May 18, 2012

Doing a Conversion from String to a Number in C#

In C, there is a nice function that converts strings to integers without throwing exceptions.  I use atoi all of the time.  In C#, I have used the convert class for a long time in order to accomplish a similar task.  The only I always had with it, is that it throws and exception of "Input string was not in a correct format" if the string is not a number.  That really is not an efficient way of handling the conversion especially if you are doing multiple of them and the performance.

There is a method in the structure for each type of number called TryParse.  This method will try to convert the number and return a bool value on whether it did or not.  It is much more efficient at handling potential errors.  Below, I have put an example that shows both ways of converting.



using System;


class Program
{
    static string X = "99";
    static string Y = "X1";


    static void Main(string[] args)
    {
        //call the functions for each string and see what we get
        int retval = 0;


        retval = use_convert(X);
        retval = use_try_parse(X);


        retval = use_convert(Y);
        retval = use_try_parse(Y);
    }


    static int use_convert(string theVal)
    {
        int A = 0;
        try
        {
            A = Convert.ToInt32(theVal);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }


        return A;
    }


    static int use_try_parse(string theVal)
    {
        int A = 0;
        bool isConverted;
        try
        {
            isConverted = Int32.TryParse(theVal, out A);


            if (!isConverted)
                Console.WriteLine("Did not convert number");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }


        return A;
    }


}


In the above example, you can see how the 2 methods work and what they will return for each string.



No comments:

Post a Comment