[ACCEPTED]-Using Int32.ToString() without Format and IFormatProvider. Why do I get the CA1305 warning?-globalization

Accepted answer
Score: 11

There are things which I would imagine could easily 3 affect the result:

  • Whether digits are substituted (not sure if this affects ToString)
  • Whether digits are grouped (not sure if NumberFormatInfo will ever group digits in an integer just from this sort of ToString call)
  • The negative sign (this could easily be significant)

Short but complete example 2 of how it could affect things, using the 1 NegativeSign property:

using System;
using System.Globalization;
using System.Threading;

class Test
{
    static void Main()
    {
        int x = -10;
        Console.WriteLine(x.ToString());

        CultureInfo culture = Thread.CurrentThread.CurrentCulture;
        // Make a writable clone
        culture = (CultureInfo) culture.Clone();
        culture.NumberFormat.NegativeSign = "!!!";

        Thread.CurrentThread.CurrentCulture = culture;
        Console.WriteLine(x.ToString());
    }
}

Output:

-10
!!!10
Score: 4

If you take a look at the NumberFormatInfo Class, you will see 2 that some properties apply to integers, such 1 as PositiveSign or Group Separators for example.

Score: 4

Even if the format actually doesn't differ 13 between cultures, you get the warning beacuse 12 you are actually doing a call using culture 11 information that looks like it doesn't contain 10 any culture information. The warning isn't 9 so much concerned about whether the culture 8 information makes any difference, rather 7 that the code hides the information that 6 culture information is used at all.

The parameterless 5 call to ToString will in turn make a call to ToString(CultureInfo.CurrentCulture). The 4 parameterless call hides this information, so 3 you should make the call where you show 2 which culture information it is that you 1 want to use in the call.

More Related questions