C#idiomatic C#
ca1311fundamentals/code-analysis/quality-rules

Code analysis

CA1311: Specify a culture or use an invariant version

Learn about code analysis rule CA1311: Specify a culture or use an invariant version

CA1311 Globalization enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

A call is made to System.String.ToUpper or System.String.ToLower without specifying a culture.

Rule description

Specify a culture or use an invariant culture to avoid implicit dependency on the current culture when calling ToUpper or ToLower. Using an invariant culture yields consistent results regardless of the culture of an application.

How to fix violations

Instead of calling the parameterless System.String.ToUpper or System.String.ToLower methods, call System.String.ToUpper(System.Globalization.CultureInfo) or System.String.ToUpperInvariant, or System.String.ToLower(System.Globalization.CultureInfo) or System.String.ToLowerInvariant.

Example

The following code snippet shows a violation of rule CA1311:

csharp
string s = "hello";
s = s.ToLower();
vb
Dim s As String = "hello"
s.ToLower()

The following code snippet fixes the violation:

csharp
string s = "hello";
s = s.ToLowerInvariant();
vb
Dim s As String = "hello"
s.ToLowerInvariant()

When to suppress warnings

It's safe to suppress a warning from this rule if you're certain that System.Threading.Thread.CurrentCulture will never change.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA1311
// The code that's violating the rule is on this line.
#pragma warning restore CA1311

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA1311.severity = none

For more information, see How to suppress code analysis warnings.

See also