Why does Convert.ToInt32 accept IFormatProvider?

6.2k views Asked by At

It makes sense for me to have following overload in Convert class

public static double ToDouble(string value, IFormatProvider provider);

examples:

Console.WriteLine(Convert.ToDouble("3223.2", CultureInfo.InvariantCulture)); // success
Console.WriteLine(Convert.ToDouble("3223,2", new CultureInfo("fr-FR"))); // success
Console.WriteLine(Convert.ToDouble("3223.2", new CultureInfo("fr-FR"))); // failure

But what is an example of using following overload?

public static int ToInt32(string value, IFormatProvider provider);

Everything fails below:

Console.WriteLine(Convert.ToInt32("3223.2", CultureInfo.InvariantCulture));
Console.WriteLine(Convert.ToInt32("3223,2", new CultureInfo("fr-FR")));
Console.WriteLine(Convert.ToInt32("3223.2", new CultureInfo("fr-FR")));

In other words are there any valid string representations of integer (in any culture) which can not be converted to int without specifying IFormatProvider?

1

There are 1 answers

2
Steve On BEST ANSWER

When you use the simple version of Convert.ToInt32 you are still using the overload that takes the readonly CultureInfo.CurrentCulture, as you can see if you look at the reference source of Convert.ToInt32

public static int ToInt32(String value) {
    if (value == null)
        return 0;
    return Int32.Parse(value, CultureInfo.CurrentCulture);
}

The point is, a lot of cultures, custom made or not, could use different characters also for common operations like a conversion and need a proper support structure.

Here an example of an odd use of custom CultureInfo that allow a weird conversion of a string to an integer

CultureInfo ci = new CultureInfo("it-IT");
ci.NumberFormat.NegativeSign = "@";

int number = Convert.ToInt32("@10", ci);
Console.WriteLine(number);