In my code I frequently use the following Converts:
Convert.ToInt32(value, Cultureinfo.InvariantCulture);
Convert.ToDecimal(value, CultureInfo.InvariantCulture);
I now do like to use TryParse functions because of recent errors. I'm not entirely sure if i'm correct in using the following equivalents as I do not completely understand the NumberStyles enum.
Int64.TryParse(value, NumberStyles.Any, CultureInfo.invariantCulture, out output);
Decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out output);
EDIT BELOW after answers
The following code should then be the correct alternative:
Int64.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out output);
Decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out output);
You can read about NumberStyles
in the documentation. Essentially it allows you to specify what sort of text will parse.
If you want to be as flexible as possible, then NumberStyles.Any
is the 'widest' option.
Convert.ToInt32
is equivalent to using int.Parse
and Convert.ToDecimal
is equivalent to using decimal.Parse
- they delegate to these methods.
Per the documentation for int.Parse
, the default is NumberStyles.Integer
. And per the documentation for decimal.Parse
, the default is NumberStyles.Number
. If you want to be consistent with the behaviour of Convert.ToInt32
and Convert.ToDecimal
, you should use these values.