23 Sep 2010

In my previous post, I described how to convert a String to an Int32 making sure that Convert.ToInt32 works all the time for positive integers.

Now, there is still an issue with that method: when the integer is negative. In that case, adding a 0 in front of it does not work and makes the conversion throw a FormatException, as the underlying parse chokes on the “0-”.

Now, the obvious ultimate solution to that problem is simply to write an extension method for DataRow to try to parse the value as an Int32:

internal static int FieldAsInt32(this DataRow dataRow, String columnName, int defaultValue)
{
    var fieldValue = dataRow.Field<String>(columnName);

    int value;

    if (Int32.TryParse(fieldValue, out value))
    {
        return value;
    }
    else
    {
        return defaultValue;
    }

}

internal static int FieldAsInt32(this DataRow dataRow, String columnName)
{
    return dataRow.FieldAsInt32(columnName, 0);
}

I added an overload that takes the default value, i.e. the value that is to be returned if the parse fails. The default for that is 0. This might not be useful in all cases, but in our case this field is used to order elements, so if it can be parsed, it has to return a very high value to make sure it is the latest in the ordered sequence.



blog comments powered by Disqus