Hello,
I want to make a generic string to numeric converter, and provide it as a string extension, so I wrote the following code:
public static bool TryParse<T>( this string text, out T result, IFormatProvider formatProvider ) where T : struct
try
{
result = (T)Convert.ChangeType( text, typeof( T ), formatProvider );
return true;
}
catch(...
I call it like this:
int value;
var ok = "123".TryParse(out value, NumberFormatInfo.CurrentInfo)
It works fine until I want to use a group separator: As I live in France, where the thousand separator is a space and the decimal separator is a comma, the string "1 234 567,89" should be equals to 1234567.89 (in Invariant culture). But, the function crashes!
When a try to perform a non generic conversion, like double.Parse(...),
I can use an overload which accepts a NumberStyles parameter. I specify NumberStyles.Number and this time it works!
So, the questions are :
- Why the parsing does not respect my NumberFormatInfo (where the NumberGroupSeparator is well specified to a space, as I specified in my OS)
- How could I make work the generic version with Convert.ChangeTime, as it has no overload wich accepts a NumberStyles parameter ?