CA1305: int.Parse(String)
Asked Answered
C

2

9

I am getting a CA1305 Warning.

Microsoft.Globalization : Because the behavior of 'int.Parse(string)' could vary based on the current user's locale settings, replace this call in '_Default.CalculateImageButton_Click(object, ImageClickEventArgs)' with a call to 'int.Parse(string, IFormatProvider)'. If the result of 'int.Parse(string, IFormatProvider)' will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'.

What exactly can go wrong if I omit specifying the culture when parsing Int32?

Cioffred answered 12/6, 2009 at 2:32 Comment(0)
A
15

It means that when you read "1,234" from a data file or Database record, then try to cast it to an Int via Parse, you'll get 1234 in America and 1 in Germany. The warning gives good advice - if you're interacting with the user, specify CurrentCulture (thanks Andrew!), and if you're interacting with a filesystem or database (or anything !user), use InvariantCulture

Ant answered 12/6, 2009 at 2:35 Comment(1)
I believe CurrentUICulture is ONLY for pulling string resources out. For all formatting, you should use CurrentCulture (notice lack of UI). Otherwise, certain cultures will cause your code to throw. See code.google.com/p/dotnetopenid/issues/detail?id=60 for an example of a bug caused by this.Mascara
B
2

If you are parsing an integer, it may have thousand separators, which can be "," or "." depending on the locale.

Beardsley answered 12/6, 2009 at 2:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.