Sunday, 15 July 2012

Implementing Convert.ToInt32(string)

Earlier today I used the static helper method System.Convert.ToInt32(string). I thought it would be interesting to have a go at writing my own version of this method.
public static int ConvertToInt32(string integerAsString)
{
    var result = 0;
    var positiveSigned = integerAsString[0] == '+';
    var negativeSigned = integerAsString[0] == '-';

    for (var i = (positiveSigned || negativeSigned) ? 1 : 0; 
        i < integerAsString.Length; 
        i++)
    {
        var currentCharAsInt = (int) integerAsString[i] - (int) '0';

        if (currentCharAsInt < 0 || currentCharAsInt > 9)
            throw new ArgumentException(
                string.Format("The String value '{0}' " + 
                    "is not in a recognisable format.", 
                        integerAsString));

        result *= 10;
        result += currentCharAsInt;
    }

    return (negativeSigned) ? -result : result;
}