May 2, 2009

Parse integers safely

Most of the times when we write code there is a need of data-type conversion. We may need to convert string into boolean, string into integers etc. Using Convert class to do these type of conversion is commonplace. But this is an error-prone practice as it may generate exception if the input is not convertible to the target type.

So one can use the strategy explained below for converting string to integer-

private void testConversion()

        string tempString = "10";
        int safeInt = 0;
        int defaultValue = 1000;
        safeInt = int.TryParse(inputValue, out safeInt ) ?  safeInt : defaultValue ;

}

Here almost all built-in types have TryParse static function which can be used for safe type parsing. In this example, int.TryParse parses string into integer and save that converted value in out variable and will return a true value. If the string is not convertible it will return a false value. In case of false value, we can assign a default value to our final variable.

Similar strategy can be employed for other data-type conversions, try it or find me here to help. Cheers!

Hope this will make your code more safer.

No comments:

Post a Comment