FxC1801 : DoNotUseParseAndTostringToConvertTypes

TypeName DoNotUseParseAndTostringToConvertTypes
CheckId FxC1801
Category FxCopContrib.Performance
Breaking Change Non-breaking

Cause

A type conversion has been detected that first converts a value to string and then tries to parse that string into a different type.

Rule Description

If a value is being converted from one type to another a loss of precision might occur if the value is first converted to string an then parsed again. For certain types (such as DateTime), round-tripping might not succeed depending on the culture settings. And converting values can often be done in a much faster way than round-tripping through string.

How to fix violations

To fix a violation of this rule, either use a direct cast, the as keyword or convert the value using Convert.ToDesiredType.

When to suppress warnings

There are no valid reasons to suppress this warning.

Example

You are reading the value of a row from a DataReader. You want to retrieve the value as an Integer.

Bad Example
public void BadMethod(IDataReader reader)
{
     int value = int.Parse(reader.GetValue(1).ToString());
}

Good Example
public void GoodMethod(IDataReader reader)
{
     int value = reader.GetInt32(1);
}

Last edited Jan 15, 2013 at 8:47 PM by jessehouwing, version 6

Comments

No comments yet.