All rules
CA1305Globalization Enabled by default: No MS default: Suggestion

Specify IFormatProvider

Pass an explicit culture / format provider to formatting APIs.

Microsoft docs

Description

Methods that format or parse values should be given an explicit IFormatProvider to avoid culture-dependent behavior.

Cause

A call is made to a method that has an overload that accepts a System.IFormatProvider argument, and that overload isn't called.

This rule ignores calls to .NET methods that are documented as ignoring the System.IFormatProvider parameter. The rule also ignores the following methods:

  • System.Activator.CreateInstance
  • System.Resources.ResourceManager.GetObject
  • System.Resources.ResourceManager.GetString
  • System.Boolean.ToString
  • System.Char.ToString
  • System.Guid.ToString

Why it matters

Relying on the current culture causes bugs that only appear on machines with different locale settings.

How to fix violations

To fix a violation of this rule, use the overload that takes an System.IFormatProvider argument. Or, to use the invariant culture, use a C# interpolated string and pass it to System.String.Create(System.IFormatProvider,System.Runtime.CompilerServices.DefaultInterpolatedStringHandler@) along with System.Globalization.CultureInfo.InvariantCulture, for example:

Examples

Avoid
var s = value.ToString();
Prefer
var s = value.ToString(CultureInfo.InvariantCulture);

When to suppress

It is safe to suppress a warning from this rule when it is certain that the default format is the correct choice, and where code maintainability is not an important development priority.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0