Using the InvariantCulture Property

The InvariantCulture property represents neither a neutral nor a specific culture. It represents a third type of culture that is culture-insensitive. It is associated with the English language but not with a country or region. Your applications can use this property with almost any method in the System.Globalization namespace that requires a culture. However, an application should use the invariant culture only for processes that require culture-independent results, such as formatting and parsing data that is persisted to a file. In other cases, it produces results that might be linguistically incorrect or culturally inappropriate.

Security Considerations

If a security decision will be made based on the result of a string comparison or case change, your application should use an ordinal comparison that ignores case instead of using InvariantCulture. The default implementations of methods such as String.Compare and String.ToUpper use the CurrentCulture property. Code that performs culture-sensitive string operations can cause security vulnerabilities if CurrentCulture is changed or if the culture on the computer running the code differs from the culture used to test the code. The behavior that you expect when writing a string operation differs from the actual behavior of your code on the executing computer. In contrast, an ordinal comparison depends solely on the binary value of the compared characters.

String Operations

If your application needs to perform a culture-sensitive string operation that is not affected by the value of CurrentCulture, it should use a method that accepts a CultureInfo parameter. The application should specify the value of the InvariantCulture property for this parameter. The application should use the property with methods such as String.Compare and String.ToUpper to eliminate cultural variations and ensure consistent results. For more information about using the InvariantCulture property to perform culture-insensitive string operations, see Culture-Insensitive String Operations.

Persisting Data

The InvariantCulture property is useful for storing data that will not be displayed directly to users. Storing data in a culture-independent format guarantees a known format that does not change. When users from different cultures access the data, it can be formatted appropriately based on specific user. For example, if your application stores DateTime types in a text file, formatted for the invariant culture, the application should use the InvariantCulture property when calling ToString to store the strings and the Parse method to retrieve the strings. This technique ensures that the underlying values of the DateTime types do not change when the data is read or written by users from different cultures.

The following code example demonstrates how to initialize a CultureInfo object with the invariant culture by using an empty string ("") or InvariantCulture.

' The following lines are equivalent.
CultureInfo Invc = New CultureInfo("")
CultureInfo Invc = CultureInfo.InvariantCulture
// The following lines are equivalent.
CultureInfo Invc = New CultureInfo("");
CultureInfo Invc = CultureInfo.InvariantCulture;

The following code example illustrates writing a DateTime object to a file as a string formatted for the invariant culture using the ToString method. The string is then read from the file in the invariant culture format and parsed to a DateTime object using the Parse method. The DateTime object is then formatted and displayed for the cultures "fr-FR" and "ja-JP".

Imports System
Imports System.IO
Imports System.Globalization
Imports Microsoft.VisualBasic

Public Class TextToFile
   Private const FILE_NAME As String = "MyDateFile.txt"   
   
   Public Shared Sub Main()
      If File.Exists(FILE_NAME) Then
         Console.WriteLine("{0} already exists!", FILE_NAME)
         Return
      End If

      Dim sw As StreamWriter = File.CreateText(FILE_NAME)
      
      'Creates a DateTime.
      Dim dtIn As DateTime = DateTime.Now
      Dim InvC As CultureInfo = CultureInfo.InvariantCulture
      ' Writes the string to the file formatted for InvariantCulture.
      sw.WriteLine(dtIn.ToString("d", InvC))
      sw.Close()
      
      If Not File.Exists(FILE_NAME) Then
         Console.WriteLine("{0} does not exist!", FILE_NAME)
         Return
      End If
      
      Dim sr As StreamReader = File.OpenText(FILE_NAME)
      Dim filedate As String
      filedate = sr.Readline()
      While Not filedate Is Nothing
         Console.WriteLine(ControlChars.Newline + "The date stored in _
            the file formatted for the invariant culture is:" + _
            ControlChars.Newline + " {0}", filedate )
         
         ' Creates a new DateTime and parses the 
         ' string stored in the file.
         Dim dtout as DateTime = DateTime.Parse(filedate, InvC)
         
         ' Creates a CultureInfo set to "fr-FR".
         Dim frc As New CultureInfo("fr-FR")
         ' Displays the date formatted for the "fr-FR" culture.
         Console.WriteLine(ControlChars.Newline + "The date read from _
            the file and formatted for the culture ""fr-FR"" is:" + _
            ControlChars.Newline + " {0}", dtout.ToString("d", frc))
         
         ' Creates a CultureInfo set to "ja-JP".
         Dim jpn As New CultureInfo("ja-JP")
         ' Displays the date formatted for the "ja-JP" culture.
         Console.WriteLine(ControlChars.Newline + "The date read from _
            the file and formatted for the culture ""ja-JP"" is:" + _
            ControlChars.Newline + " {0}", dtout.ToString("d", jpn))
        
        filedate = sr.Readline()
      End While
      
      Console.WriteLine(ControlChars.Newline + "The end of the stream _
         has been reached.")
      sr.Close()
   End Sub
End Class
using System;
using System.IO;
using System.Globalization;

public class TextToFile 
{
   private const string FILE_NAME = "MyDateFile.txt";
   public static void Main(String[] args) 
   {
      if (File.Exists(FILE_NAME)) 
      {
         Console.WriteLine("{0} already exists!", FILE_NAME);
         return;
      }
      StreamWriter sw = File.CreateText(FILE_NAME);
      
      // Creates a DateTime.      
      DateTime dtIn = DateTime.Now;
      // Creates a CultureInfo set to InvariantCulture.
      CultureInfo InvC = new CultureInfo("");
      // Converts dt to a string formatted for InvariantCulture,
      // and writes it to a file.
      sw.WriteLine (dtIn.ToString("d",InvC));
      sw.Close();

      if (!File.Exists(FILE_NAME)) 
      {
         Console.WriteLine("{0} does not exist!", FILE_NAME);
         return;
      }
      StreamReader sr = File.OpenText(FILE_NAME);
      String date;
      while ((date=sr.ReadLine())!=null) 
      {
         Console.WriteLine("\nThe date stored in the file formatted for 
               the invariant culture is:\n{0}" , date);    

         // Parses the string stored in the file,
         // and stores it in a DateTime.
         DateTime dtout = DateTime.Parse(date, InvC);

         // Creates a CultureInfo set to "fr-FR".
         CultureInfo frc = new CultureInfo("fr-FR");
         // Displays the date formatted for the "fr-FR" culture.
         Console.WriteLine("\nThe date read from the file and formatted 
               for the culture \"fr-FR\" is:\n{0}" , dtout.ToString("d", 
               frc));

         // Creates a CultureInfo set to "ja-JP".
         CultureInfo jpn= new CultureInfo("ja-JP");
         // Displays the date formatted for the "ja-JP" culture.
         Console.WriteLine("\nThe date read from the file and formatted 
               for the culture \"ja-JP\" is:\n{0}" , dtout.ToString("d", 
               jpn));
      }
      Console.WriteLine ("\nThe end of the stream has been reached.");
      sr.Close();
   }
}

This code produces the following output:

The date stored in the file formatted for the invariant culture is:
07/24/2001

The date read from the file and formatted for the culture "fr-FR" is:
24/07/2001

The date read from the file and formatted for the culture "ja-JP" is:
2001/07/24

The end of the stream has been reached.

See Also

Concepts

Using the CultureInfo Class