In the following example, BadMethod causes two violations of this rule. GoodMethod corrects the first violation by passing the invariant culture to System.String.Compare, and corrects the second violation by passing the current culture to ToLower because string3 is being displayed to the user.
|
using System;
using System.Globalization;
namespace GlobalizationLibrary
{
public class CultureInfoTest
{
public void BadMethod(String string1, String string2, String string3)
{
if(string.Compare(string1, string2, false) == 0)
{
Console.WriteLine(string3.ToLower());
}
}
public void GoodMethod(String string1, String string2, String string3)
{
if(string.Compare(string1, string2, false,
CultureInfo.InvariantCulture) == 0)
{
Console.WriteLine(string3.ToLower(CultureInfo.CurrentCulture));
}
}
}
}
|
The following example shows the effect of current culture on the default IFormatProvider selected by the DateTime type.
|
using System;
using System.Globalization;
using System.Threading;
namespace GlobalLibGlobalLibrary
{
public class IFormatProviderTest
{
public static void Main()
{
string dt = "6/4/1900 12:15:12";
// The default behavior of DateTime.Parse is to use
// the current culture.
// Violates rule: SpecifyIFormatProvider.
DateTime myDateTime = DateTime.Parse(dt);
Console.WriteLine(myDateTime);
// Change the current culture to the French culture,
// and parsing the same string yields a different value.
Thread.CurrentThread.CurrentCulture = new CultureInfo("Fr-fr", true);
myDateTime = DateTime.Parse(dt);
Console.WriteLine(myDateTime);
}
}
}
|
This example produces the following output:
|
6/4/1900 12:15:12 PM
06/04/1900 12:15:12
|