1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
5 ////////////////////////////////////////////////////////////////////////////
9 // Purpose: This class represents the software preferences of a particular
10 // culture or community. It includes information such as the
11 // language, writing system, and a calendar used by the culture
12 // as well as methods for common operations such as printing
13 // dates and sorting strings.
17 // !!!! NOTE WHEN CHANGING THIS CLASS !!!!
19 // If adding or removing members to this class, please update CultureInfoBaseObject
20 // in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be
21 // different than the order in which members are declared. For instance, all
22 // reference types will come first in the class before value types (like ints, bools, etc)
23 // regardless of the order in which they are declared. The best way to see the
24 // actual order of the class is to do a !dumpobj on an instance of the managed
25 // object inside of the debugger.
27 ////////////////////////////////////////////////////////////////////////////
29 namespace System.Globalization {
31 using System.Security;
32 using System.Threading;
33 using System.Collections;
35 using System.Runtime.CompilerServices;
36 using System.Runtime.InteropServices;
37 using System.Runtime.Serialization;
38 using System.Runtime.Versioning;
39 using System.Security.Permissions;
40 using System.Reflection;
41 using Microsoft.Win32;
42 using System.Diagnostics.Contracts;
43 using System.Resources;
46 [System.Runtime.InteropServices.ComVisible(true)]
47 public partial class CultureInfo : ICloneable, IFormatProvider {
48 //--------------------------------------------------------------------//
49 // Internal Information //
50 //--------------------------------------------------------------------//
52 //--------------------------------------------------------------------//
53 // Data members to be serialized:
54 //--------------------------------------------------------------------//
56 // We use an RFC4646 type string to construct CultureInfo.
57 // This string is stored in m_name and is authoritative.
58 // We use the m_cultureData to get the data for our object
61 // WARNING: All member fields declared here must also be in ndp/clr/src/vm/object.h
62 // WARNING: They aren't really private because object.h can access them, but other C# stuff cannot
63 // WARNING: The type loader will rearrange class member offsets so the mscorwks!CultureInfoBaseObject
64 // WARNING: must be manually structured to match the true loaded class layout
66 internal bool m_isReadOnly;
67 internal CompareInfo compareInfo;
68 internal TextInfo textInfo;
69 // Not serialized for now since we only build it privately for use in the CARIB (so rebuilding is OK)
71 [NonSerialized]internal RegionInfo regionInfo;
73 internal NumberFormatInfo numInfo;
74 internal DateTimeFormatInfo dateTimeInfo;
75 internal Calendar calendar;
76 [OptionalField(VersionAdded = 1)]
77 internal int m_dataItem; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
78 [OptionalField(VersionAdded = 1)]
79 internal int cultureID = 0x007f; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
81 // The CultureData instance that we are going to read data from.
82 // For supported culture, this will be the CultureData instance that read data from mscorlib assembly.
83 // For customized culture, this will be the CultureData instance that read data from user customized culture binary file.
85 [NonSerialized]internal CultureData m_cultureData;
87 [NonSerialized]internal bool m_isInherited;
88 #if FEATURE_LEAK_CULTURE_INFO
89 [NonSerialized]private bool m_isSafeCrossDomain;
90 [NonSerialized]private int m_createdDomainID;
91 #endif // !FEATURE_CORECLR
93 [NonSerialized]private CultureInfo m_consoleFallbackCulture;
94 #endif // !FEATURE_CORECLR
96 // Names are confusing. Here are 3 names we have:
98 // new CultureInfo() m_name m_nonSortName m_sortName
99 // en-US en-US en-US en-US
100 // de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb
101 // fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US)
104 // Note that in Silverlight we ask the OS for the text and sort behavior, so the
105 // textinfo and compareinfo names are the same as the name
107 // Note that the name used to be serialized for Everett; it is now serialized
108 // because alernate sorts can have alternate names.
109 // This has a de-DE, de-DE_phoneb or fj-FJ style name
110 internal string m_name;
112 // This will hold the non sorting name to be returned from CultureInfo.Name property.
113 // This has a de-DE style name even for de-DE_phoneb type cultures
114 [NonSerialized]private string m_nonSortName;
116 // This will hold the sorting name to be returned from CultureInfo.SortName property.
117 // This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ.
118 // Otherwise its the sort name, ie: de-DE or de-DE_phoneb
119 [NonSerialized]private string m_sortName;
122 //--------------------------------------------------------------------//
124 // Static data members
126 //--------------------------------------------------------------------//
128 //Get the current user default culture. This one is almost always used, so we create it by default.
129 private static volatile CultureInfo s_userDefaultCulture;
132 // All of the following will be created on demand.
135 //The Invariant culture;
136 private static volatile CultureInfo s_InvariantCultureInfo;
138 //The culture used in the user interface. This is mostly used to load correct localized resources.
139 private static volatile CultureInfo s_userDefaultUICulture;
141 //This is the UI culture used to install the OS.
142 private static volatile CultureInfo s_InstalledUICultureInfo;
144 //These are defaults that we use if a thread has not opted into having an explicit culture
145 private static volatile CultureInfo s_DefaultThreadCurrentUICulture;
146 private static volatile CultureInfo s_DefaultThreadCurrentCulture;
148 //This is a cache of all previously created cultures. Valid keys are LCIDs or the name. We use two hashtables to track them,
149 // depending on how they are called.
150 private static volatile Hashtable s_LcidCachedCultures;
151 private static volatile Hashtable s_NameCachedCultures;
154 // When running under AppX, we use this to get some information about the language list
156 private static volatile WindowsRuntimeResourceManagerBase s_WindowsRuntimeResourceManager;
159 private static bool ts_IsDoingAppXCultureInfoLookup;
162 //The parent culture.
163 [NonSerialized]private CultureInfo m_parent;
165 // LOCALE constants of interest to us internally and privately for LCID functions
166 // (ie: avoid using these and use names if possible)
167 internal const int LOCALE_NEUTRAL = 0x0000;
168 private const int LOCALE_USER_DEFAULT = 0x0400;
169 private const int LOCALE_SYSTEM_DEFAULT = 0x0800;
170 internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00;
171 internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000;
172 internal const int LOCALE_INVARIANT = 0x007F;
173 private const int LOCALE_TRADITIONAL_SPANISH = 0x040a;
176 // The CultureData instance that reads the data provided by our CultureData class.
178 //Using a field initializer rather than a static constructor so that the whole class can be lazy
180 private static readonly bool init = Init();
181 private static bool Init()
184 if (s_InvariantCultureInfo == null)
186 CultureInfo temp = new CultureInfo("", false);
187 temp.m_isReadOnly = true;
188 s_InvariantCultureInfo = temp;
190 // First we set it to Invariant in case someone needs it before we're done finding it.
191 // For example, if we throw an exception in InitUserDefaultCulture, we will still need an valid
192 // s_userDefaultCulture to be used in Thread.CurrentCulture.
193 s_userDefaultCulture = s_userDefaultUICulture = s_InvariantCultureInfo;
195 s_userDefaultCulture = InitUserDefaultCulture();
196 s_userDefaultUICulture = InitUserDefaultUICulture();
200 [System.Security.SecuritySafeCritical] // auto-generated
201 static CultureInfo InitUserDefaultCulture()
203 String strDefault = GetDefaultLocaleName(LOCALE_USER_DEFAULT);
204 if (strDefault == null)
206 strDefault = GetDefaultLocaleName(LOCALE_SYSTEM_DEFAULT);
208 if (strDefault == null)
210 // If system default doesn't work, keep using the invariant
211 return (CultureInfo.InvariantCulture);
214 CultureInfo temp = GetCultureByName(strDefault, true);
216 temp.m_isReadOnly = true;
221 static CultureInfo InitUserDefaultUICulture()
223 String strDefault = GetUserDefaultUILanguage();
225 // In most of cases, UserDefaultCulture == UserDefaultUICulture, so we should use the same instance if possible.
226 if (strDefault == UserDefaultCulture.Name)
228 return (UserDefaultCulture);
231 CultureInfo temp = GetCultureByName( strDefault, true);
235 return (CultureInfo.InvariantCulture);
238 temp.m_isReadOnly = true;
244 [SecuritySafeCritical]
245 internal static CultureInfo GetCultureInfoForUserPreferredLanguageInAppX()
247 // If a call to GetCultureInfoForUserPreferredLanguageInAppX() generated a recursive
248 // call to itself, return null, since we don't want to stack overflow. For example,
249 // this can happen if some code in this method ends up calling CultureInfo.CurrentCulture
250 // (which is common on check'd build because of BCLDebug logging which calls Int32.ToString()).
251 // In this case, returning null will mean CultureInfo.CurrentCulture gets the default Win32
252 // value, which should be fine.
253 if(ts_IsDoingAppXCultureInfoLookup)
258 // If running within a compilation process (mscorsvw.exe, for example), it is illegal to
259 // load any non-mscorlib assembly for execution. Since WindowsRuntimeResourceManager lives
260 // in System.Runtime.WindowsRuntime, caller will need to fall back to default Win32 value,
261 // which should be fine because we should only ever need to access FX resources during NGEN.
262 // FX resources are always loaded from satellite assemblies - even in AppX processes (see the
263 // comments in code:System.Resources.ResourceManager.SetAppXConfiguration for more details).
264 if (AppDomain.IsAppXNGen)
269 CultureInfo toReturn = null;
273 ts_IsDoingAppXCultureInfoLookup = true;
275 if(s_WindowsRuntimeResourceManager == null)
277 s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
280 toReturn = s_WindowsRuntimeResourceManager.GlobalResourceContextBestFitCultureInfo;
284 ts_IsDoingAppXCultureInfoLookup = false;
290 [SecuritySafeCritical]
291 internal static bool SetCultureInfoForUserPreferredLanguageInAppX(CultureInfo ci)
293 // If running within a compilation process (mscorsvw.exe, for example), it is illegal to
294 // load any non-mscorlib assembly for execution. Since WindowsRuntimeResourceManager lives
295 // in System.Runtime.WindowsRuntime, caller will need to fall back to default Win32 value,
296 // which should be fine because we should only ever need to access FX resources during NGEN.
297 // FX resources are always loaded from satellite assemblies - even in AppX processes (see the
298 // comments in code:System.Resources.ResourceManager.SetAppXConfiguration for more details).
299 if (AppDomain.IsAppXNGen)
304 if (s_WindowsRuntimeResourceManager == null)
306 s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
309 return s_WindowsRuntimeResourceManager.SetGlobalResourceContextDefaultCulture(ci);
313 ////////////////////////////////////////////////////////////////////////
315 // CultureInfo Constructors
317 ////////////////////////////////////////////////////////////////////////
320 public CultureInfo(String name) : this(name, true) {
324 public CultureInfo(String name, bool useUserOverride) {
326 throw new ArgumentNullException("name",
327 Environment.GetResourceString("ArgumentNull_String"));
329 Contract.EndContractBlock();
331 // Get our data providing record
332 this.m_cultureData = CultureData.GetCultureData(name, useUserOverride);
334 if (this.m_cultureData == null) {
335 throw new CultureNotFoundException("name", name, Environment.GetResourceString("Argument_CultureNotSupported"));
338 this.m_name = this.m_cultureData.CultureName;
339 this.m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
344 public CultureInfo(int culture) : this(culture, true) {
347 public CultureInfo(int culture, bool useUserOverride) {
348 // We don't check for other invalid LCIDS here...
350 throw new ArgumentOutOfRangeException("culture",
351 Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
353 Contract.EndContractBlock();
355 InitializeFromCultureId(culture, useUserOverride);
358 private void InitializeFromCultureId(int culture, bool useUserOverride)
362 case LOCALE_CUSTOM_DEFAULT:
363 case LOCALE_SYSTEM_DEFAULT:
365 case LOCALE_USER_DEFAULT:
366 case LOCALE_CUSTOM_UNSPECIFIED:
367 // Can't support unknown custom cultures and we do not support neutral or
368 // non-custom user locales.
369 throw new CultureNotFoundException(
370 "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported"));
373 // Now see if this LCID is supported in the system default CultureData table.
374 this.m_cultureData = CultureData.GetCultureData(culture, useUserOverride);
377 this.m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
378 this.m_name = this.m_cultureData.CultureName;
380 #endif // FEATURE_USE_LCID
383 // CheckDomainSafetyObject throw if the object is customized object which cannot be attached to
384 // other object (like CultureInfo or DateTimeFormatInfo).
387 internal static void CheckDomainSafetyObject(Object obj, Object container)
389 if (obj.GetType().Assembly != typeof(System.Globalization.CultureInfo).Assembly) {
391 throw new InvalidOperationException(
393 CultureInfo.CurrentCulture,
394 Environment.GetResourceString("InvalidOperation_SubclassedObject"),
396 container.GetType()));
398 Contract.EndContractBlock();
401 #region Serialization
402 // We need to store the override from the culture data record.
403 private bool m_useUserOverride;
406 private void OnDeserialized(StreamingContext ctx)
409 // Whidbey+ should remember our name
410 // but v1 and v1.1 did not store name -- only lcid
411 // Whidbey did not store actual alternate sort name in m_name
412 // like we do in v4 so we can't use name for alternate sort
413 // e.g. for es-ES_tradnl: v2 puts es-ES in m_name; v4 puts es-ES_tradnl
414 if (m_name == null || IsAlternateSortLcid(cultureID))
416 Contract.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
417 InitializeFromCultureId(cultureID, m_useUserOverride);
422 Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
424 this.m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride);
425 if (this.m_cultureData == null)
426 throw new CultureNotFoundException(
427 "m_name", m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
432 m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
434 // in case we have non customized CultureInfo object we shouldn't allow any customized object
435 // to be attached to it for cross app domain safety.
436 if (this.GetType().Assembly == typeof(System.Globalization.CultureInfo).Assembly)
438 if (textInfo != null)
440 CheckDomainSafetyObject(textInfo, this);
443 if (compareInfo != null)
445 CheckDomainSafetyObject(compareInfo, this);
451 // A locale ID is a 32 bit value which is the combination of a
452 // language ID, a sort ID, and a reserved area. The bits are
453 // allocated as follows:
455 // +------------------------+-------+--------------------------------+
456 // | Reserved |Sort ID| Language ID |
457 // +------------------------+-------+--------------------------------+
458 // 31 20 19 16 15 0 bit
459 private const int LOCALE_SORTID_MASK = 0x000f0000;
461 static private bool IsAlternateSortLcid(int lcid)
463 if(lcid == LOCALE_TRADITIONAL_SPANISH)
468 return (lcid & LOCALE_SORTID_MASK) != 0;
473 private void OnSerializing(StreamingContext ctx)
475 this.m_name = this.m_cultureData.CultureName;
476 this.m_useUserOverride = this.m_cultureData.UseUserOverride;
478 // for compatibility with v2 serialize cultureID
479 this.cultureID = this.m_cultureData.ILANGUAGE;
482 #endregion Serialization
484 #if FEATURE_LEAK_CULTURE_INFO
485 // Is it safe to send this CultureInfo as an instance member of a Thread cross AppDomain boundaries?
486 // For Silverlight, the answer is always no.
487 internal bool IsSafeCrossDomain {
489 Contract.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
490 return m_isSafeCrossDomain;
494 internal int CreatedDomainID {
496 Contract.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
497 return m_createdDomainID;
501 internal void StartCrossDomainTracking() {
503 // If we have decided about cross domain safety of this instance, we are done
504 if (m_createdDomainID != 0)
507 // If FEATURE_LEAK_CULTURE_INFO isn't enabled, we never want to pass
508 // CultureInfo as an instance member of a Thread.
509 if (CanSendCrossDomain())
511 m_isSafeCrossDomain = true;
514 // m_createdDomainID has to be assigned last. We use it to signal that we have
515 // completed the check.
516 System.Threading.Thread.MemoryBarrier();
517 m_createdDomainID = Thread.GetDomainID();
519 #endif // FEATURE_LEAK_CULTURE_INFO
521 // Is it safe to pass the CultureInfo cross AppDomain boundaries, not necessarily as an instance
522 // member of Thread. This is different from IsSafeCrossDomain, which implies passing the CultureInfo
523 // as a Thread instance member.
524 internal bool CanSendCrossDomain()
527 if (this.GetType() == typeof(System.Globalization.CultureInfo))
534 // Constructor called by SQL Server's special munged culture - creates a culture with
535 // a TextInfo and CompareInfo that come from a supplied alternate source. This object
536 // is ALWAYS read-only.
537 // Note that we really cannot use an LCID version of this override as the cached
538 // name we create for it has to include both names, and the logic for this is in
539 // the GetCultureInfo override *only*.
540 internal CultureInfo(String cultureName, String textAndCompareCultureName)
542 if (cultureName==null) {
543 throw new ArgumentNullException("cultureName",
544 Environment.GetResourceString("ArgumentNull_String"));
546 Contract.EndContractBlock();
548 this.m_cultureData = CultureData.GetCultureData(cultureName, false);
549 if (this.m_cultureData == null)
550 throw new CultureNotFoundException(
551 "cultureName", cultureName, Environment.GetResourceString("Argument_CultureNotSupported"));
553 this.m_name = this.m_cultureData.CultureName;
555 CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName);
556 this.compareInfo = altCulture.CompareInfo;
557 this.textInfo = altCulture.TextInfo;
560 // We do this to try to return the system UI language and the default user languages
561 // The callers should have a fallback if this fails (like Invariant)
562 private static CultureInfo GetCultureByName(String name, bool userOverride)
564 // Try to get our culture
567 return userOverride ? new CultureInfo(name) : CultureInfo.GetCultureInfo(name);
569 catch (ArgumentException)
577 // Return a specific culture. A tad irrelevent now since we always return valid data
578 // for neutral locales.
580 // Note that there's interesting behavior that tries to find a smaller name, ala RFC4647,
581 // if we can't find a bigger name. That doesn't help with things like "zh" though, so
582 // the approach is of questionable value
584 public static CultureInfo CreateSpecificCulture(String name) {
585 Contract.Ensures(Contract.Result<CultureInfo>() != null);
590 culture = new CultureInfo(name);
591 } catch(ArgumentException) {
592 // When CultureInfo throws this exception, it may be because someone passed the form
593 // like "az-az" because it came out of an http accept lang. We should try a little
594 // parsing to perhaps fall back to "az" here and use *it* to create the neutral.
599 for(idx = 0; idx < name.Length; idx++) {
600 if('-' == name[idx]) {
602 culture = new CultureInfo(name.Substring(0, idx));
604 } catch(ArgumentException) {
605 // throw the original exception so the name in the string will be right
611 if(null == culture) {
612 // nothing to save here; throw the original exception
617 //In the most common case, they've given us a specific culture, so we'll just return that.
618 if (!(culture.IsNeutralCulture)) {
622 return (new CultureInfo(culture.m_cultureData.SSPECIFICCULTURE));
625 internal static bool VerifyCultureName(String cultureName, bool throwException)
627 // This function is used by ResourceManager.GetResourceFileName().
628 // ResourceManager searches for resource using CultureInfo.Name,
629 // so we should check against CultureInfo.Name.
631 for (int i=0; i<cultureName.Length; i++) {
632 char c = cultureName[i];
634 if (Char.IsLetterOrDigit(c) || c=='-' || c=='_') {
637 if (throwException) {
638 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidResourceCultureName", cultureName));
646 internal static bool VerifyCultureName(CultureInfo culture, bool throwException) {
647 Contract.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
649 //If we have an instance of one of our CultureInfos, the user can't have changed the
650 //name and we know that all names are valid in files.
651 if (!culture.m_isInherited) {
655 return VerifyCultureName(culture.Name, throwException);
659 ////////////////////////////////////////////////////////////////////////
663 // This instance provides methods based on the current user settings.
664 // These settings are volatile and may change over the lifetime of the
667 ////////////////////////////////////////////////////////////////////////
670 public static CultureInfo CurrentCulture
673 Contract.Ensures(Contract.Result<CultureInfo>() != null);
676 return Thread.CurrentThread.CurrentCulture;
678 // In the case of CoreCLR, Thread.m_CurrentCulture and
679 // Thread.m_CurrentUICulture are thread static so as not to let
680 // CultureInfo objects leak across AppDomain boundaries. The
681 // fact that these fields are thread static introduces overhead
682 // in accessing them (through Thread.CurrentCulture). There is
683 // also overhead in accessing Thread.CurrentThread. In this
684 // case, we can avoid the overhead of Thread.CurrentThread
685 // because these fields are thread static, and so do not
686 // require a Thread instance to be accessed.
688 if(AppDomain.IsAppXModel()) {
689 CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
694 return Thread.m_CurrentCulture ??
695 s_DefaultThreadCurrentCulture ??
696 s_userDefaultCulture ??
704 throw new ArgumentNullException("value");
707 if (AppDomain.IsAppXModel()) {
708 if (SetCultureInfoForUserPreferredLanguageInAppX(value)) {
709 // successfully set the culture, otherwise fallback to legacy path
714 Thread.CurrentThread.CurrentCulture = value;
719 // This is the equivalence of the Win32 GetUserDefaultLCID()
721 internal static CultureInfo UserDefaultCulture {
724 Contract.Ensures(Contract.Result<CultureInfo>() != null);
726 CultureInfo temp = s_userDefaultCulture;
730 // setting the s_userDefaultCulture with invariant culture before intializing it is a protection
731 // against recursion problem just in case if somebody called CurrentCulture from the CultureInfo
732 // creation path. the recursion can happen if the current user culture is a replaced custom culture.
735 s_userDefaultCulture = CultureInfo.InvariantCulture;
736 temp = InitUserDefaultCulture();
737 s_userDefaultCulture = temp;
744 // This is the equivalence of the Win32 GetUserDefaultUILanguage()
746 internal static CultureInfo UserDefaultUICulture {
748 Contract.Ensures(Contract.Result<CultureInfo>() != null);
750 CultureInfo temp = s_userDefaultUICulture;
754 // setting the s_userDefaultCulture with invariant culture before intializing it is a protection
755 // against recursion problem just in case if somebody called CurrentUICulture from the CultureInfo
756 // creation path. the recursion can happen if the current user culture is a replaced custom culture.
759 s_userDefaultUICulture = CultureInfo.InvariantCulture;
761 temp = InitUserDefaultUICulture();
762 s_userDefaultUICulture = temp;
769 public static CultureInfo CurrentUICulture {
771 Contract.Ensures(Contract.Result<CultureInfo>() != null);
774 return Thread.CurrentThread.CurrentUICulture;
776 // In the case of CoreCLR, Thread.m_CurrentCulture and
777 // Thread.m_CurrentUICulture are thread static so as not to let
778 // CultureInfo objects leak across AppDomain boundaries. The
779 // fact that these fields are thread static introduces overhead
780 // in accessing them (through Thread.CurrentCulture). There is
781 // also overhead in accessing Thread.CurrentThread. In this
782 // case, we can avoid the overhead of Thread.CurrentThread
783 // because these fields are thread static, and so do not
784 // require a Thread instance to be accessed.
786 if(AppDomain.IsAppXModel()) {
787 CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
792 return Thread.m_CurrentUICulture ??
793 s_DefaultThreadCurrentUICulture ??
794 s_userDefaultUICulture ??
795 UserDefaultUICulture;
802 throw new ArgumentNullException("value");
805 if (AppDomain.IsAppXModel()) {
806 if (SetCultureInfoForUserPreferredLanguageInAppX(value)) {
807 // successfully set the culture, otherwise fallback to legacy path
812 Thread.CurrentThread.CurrentUICulture = value;
818 // This is the equivalence of the Win32 GetSystemDefaultUILanguage()
820 public static CultureInfo InstalledUICulture {
822 Contract.Ensures(Contract.Result<CultureInfo>() != null);
824 CultureInfo temp = s_InstalledUICultureInfo;
826 String strDefault = GetSystemDefaultUILanguage();
827 temp = GetCultureByName(strDefault, true);
831 temp = InvariantCulture;
834 temp.m_isReadOnly = true;
835 s_InstalledUICultureInfo = temp;
841 public static CultureInfo DefaultThreadCurrentCulture {
843 return s_DefaultThreadCurrentCulture;
846 [System.Security.SecuritySafeCritical] // auto-generated
847 #pragma warning disable 618
848 [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
849 #pragma warning restore 618
852 // If you add pre-conditions to this method, check to see if you also need to
853 // add them to Thread.CurrentCulture.set.
855 s_DefaultThreadCurrentCulture = value;
859 public static CultureInfo DefaultThreadCurrentUICulture {
861 return s_DefaultThreadCurrentUICulture;
864 [System.Security.SecuritySafeCritical] // auto-generated
865 #pragma warning disable 618
866 [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
867 #pragma warning restore 618
870 //If they're trying to use a Culture with a name that we can't use in resource lookup,
871 //don't even let them set it on the thread.
873 // If you add more pre-conditions to this method, check to see if you also need to
874 // add them to Thread.CurrentUICulture.set.
878 CultureInfo.VerifyCultureName(value, true);
881 s_DefaultThreadCurrentUICulture = value;
885 ////////////////////////////////////////////////////////////////////////
889 // This instance provides methods, for example for casing and sorting,
890 // that are independent of the system and current user settings. It
891 // should be used only by processes such as some system services that
892 // require such invariant results (eg. file systems). In general,
893 // the results are not linguistically correct and do not match any
896 ////////////////////////////////////////////////////////////////////////
899 public static CultureInfo InvariantCulture {
902 Contract.Ensures(Contract.Result<CultureInfo>() != null);
903 return (s_InvariantCultureInfo);
908 ////////////////////////////////////////////////////////////////////////
912 // Return the parent CultureInfo for the current instance.
914 ////////////////////////////////////////////////////////////////////////
916 public virtual CultureInfo Parent
918 [System.Security.SecuritySafeCritical] // auto-generated
921 Contract.Ensures(Contract.Result<CultureInfo>() != null);
923 if (null == m_parent)
927 string parentName = this.m_cultureData.SPARENT;
929 if (String.IsNullOrEmpty(parentName))
931 m_parent = InvariantCulture;
935 m_parent = new CultureInfo(parentName, this.m_cultureData.UseUserOverride);
938 catch (ArgumentException)
940 // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant
941 // We can't allow ourselves to fail. In case of custom cultures the parent of the
942 // current custom culture isn't installed.
943 m_parent = InvariantCulture;
950 ////////////////////////////////////////////////////////////////////////
954 // Returns a properly formed culture identifier for the current
957 ////////////////////////////////////////////////////////////////////////
960 public virtual int LCID {
962 return (this.m_cultureData.ILANGUAGE);
967 ////////////////////////////////////////////////////////////////////////
971 // Essentially an LCID, though one that may be different than LCID in the case
972 // of a customized culture (LCID == LOCALE_CUSTOM_UNSPECIFIED).
974 ////////////////////////////////////////////////////////////////////////
976 [System.Runtime.InteropServices.ComVisible(false)]
977 public virtual int KeyboardLayoutId
981 int keyId = this.m_cultureData.IINPUTLANGUAGEHANDLE;
983 // Not a customized culture, return the default Keyboard layout ID, which is the same as the language ID.
989 public static CultureInfo[] GetCultures(CultureTypes types) {
990 Contract.Ensures(Contract.Result<CultureInfo[]>() != null);
991 // internally we treat UserCustomCultures as Supplementals but v2
992 // treats as Supplementals and Replacements
993 if((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture)
995 types |= CultureTypes.ReplacementCultures;
997 return (CultureData.GetCultures(types));
1000 ////////////////////////////////////////////////////////////////////////
1004 // Returns the full name of the CultureInfo. The name is in format like
1005 // "en-US" This version does NOT include sort information in the name.
1007 ////////////////////////////////////////////////////////////////////////
1008 public virtual String Name {
1010 Contract.Ensures(Contract.Result<String>() != null);
1012 // We return non sorting name here.
1013 if (this.m_nonSortName == null) {
1014 this.m_nonSortName = this.m_cultureData.SNAME;
1015 if (this.m_nonSortName == null) {
1016 this.m_nonSortName = String.Empty;
1019 return this.m_nonSortName;
1023 // This one has the sort information (ie: de-DE_phoneb)
1024 internal String SortName
1028 if (this.m_sortName == null)
1030 this.m_sortName = this.m_cultureData.SCOMPAREINFO;
1033 return this.m_sortName;
1037 #if !FEATURE_CORECLR
1038 [System.Runtime.InteropServices.ComVisible(false)]
1039 public String IetfLanguageTag
1043 Contract.Ensures(Contract.Result<String>() != null);
1045 // special case the compatibility cultures
1059 ////////////////////////////////////////////////////////////////////////
1063 // Returns the full name of the CultureInfo in the localized language.
1064 // For example, if the localized language of the runtime is Spanish and the CultureInfo is
1065 // US English, "Ingles (Estados Unidos)" will be returned.
1067 ////////////////////////////////////////////////////////////////////////
1068 public virtual String DisplayName
1070 [System.Security.SecuritySafeCritical] // auto-generated
1073 Contract.Ensures(Contract.Result<String>() != null);
1074 Contract.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
1076 return m_cultureData.SLOCALIZEDDISPLAYNAME;
1080 ////////////////////////////////////////////////////////////////////////
1084 // Returns the full name of the CultureInfo in the native language.
1085 // For example, if the CultureInfo is US English, "English
1086 // (United States)" will be returned.
1088 ////////////////////////////////////////////////////////////////////////
1089 public virtual String NativeName {
1090 [System.Security.SecuritySafeCritical] // auto-generated
1092 Contract.Ensures(Contract.Result<String>() != null);
1093 return (this.m_cultureData.SNATIVEDISPLAYNAME);
1097 ////////////////////////////////////////////////////////////////////////
1101 // Returns the full name of the CultureInfo in English.
1102 // For example, if the CultureInfo is US English, "English
1103 // (United States)" will be returned.
1105 ////////////////////////////////////////////////////////////////////////
1106 public virtual String EnglishName {
1107 [System.Security.SecuritySafeCritical] // auto-generated
1109 Contract.Ensures(Contract.Result<String>() != null);
1110 return (this.m_cultureData.SENGDISPLAYNAME);
1115 public virtual String TwoLetterISOLanguageName {
1116 [System.Security.SecuritySafeCritical] // auto-generated
1118 Contract.Ensures(Contract.Result<String>() != null);
1119 return (this.m_cultureData.SISO639LANGNAME);
1124 public virtual String ThreeLetterISOLanguageName {
1125 [System.Security.SecuritySafeCritical] // auto-generated
1127 Contract.Ensures(Contract.Result<String>() != null);
1128 return (this.m_cultureData.SISO639LANGNAME2);
1132 ////////////////////////////////////////////////////////////////////////
1134 // ThreeLetterWindowsLanguageName
1136 // Returns the 3 letter windows language name for the current instance. eg: "ENU"
1137 // The ISO names are much preferred
1139 ////////////////////////////////////////////////////////////////////////
1140 public virtual String ThreeLetterWindowsLanguageName {
1141 [System.Security.SecuritySafeCritical] // auto-generated
1143 Contract.Ensures(Contract.Result<String>() != null);
1144 return (this.m_cultureData.SABBREVLANGNAME);
1148 ////////////////////////////////////////////////////////////////////////
1150 // CompareInfo Read-Only Property
1152 // Gets the CompareInfo for this culture.
1154 ////////////////////////////////////////////////////////////////////////
1155 public virtual CompareInfo CompareInfo
1159 Contract.Ensures(Contract.Result<CompareInfo>() != null);
1161 if (this.compareInfo == null)
1163 // Since CompareInfo's don't have any overrideable properties, get the CompareInfo from
1164 // the Non-Overridden CultureInfo so that we only create one CompareInfo per culture
1165 CompareInfo temp = UseUserOverride
1166 ? GetCultureInfo(this.m_name).CompareInfo
1167 : new CompareInfo(this);
1168 if (CompatibilitySwitches.IsCompatibilityBehaviorDefined)
1170 this.compareInfo = temp;
1177 return (compareInfo);
1181 #if !FEATURE_CORECLR
1182 ////////////////////////////////////////////////////////////////////////
1186 // Gets the RegionInfo for this culture.
1188 ////////////////////////////////////////////////////////////////////////
1189 private RegionInfo Region
1193 if (regionInfo==null)
1195 // Make a new regionInfo
1196 RegionInfo tempRegionInfo = new RegionInfo(this.m_cultureData);
1197 regionInfo = tempRegionInfo;
1199 return (regionInfo);
1202 #endif // FEATURE_CORECLR
1206 ////////////////////////////////////////////////////////////////////////
1210 // Gets the TextInfo for this culture.
1212 ////////////////////////////////////////////////////////////////////////
1215 public virtual TextInfo TextInfo {
1217 Contract.Ensures(Contract.Result<TextInfo>() != null);
1221 // Make a new textInfo
1222 TextInfo tempTextInfo = new TextInfo(this.m_cultureData);
1223 tempTextInfo.SetReadOnlyState(m_isReadOnly);
1225 if (CompatibilitySwitches.IsCompatibilityBehaviorDefined)
1227 textInfo = tempTextInfo;
1231 return tempTextInfo;
1238 ////////////////////////////////////////////////////////////////////////
1242 // Implements Object.Equals(). Returns a boolean indicating whether
1243 // or not object refers to the same CultureInfo as the current instance.
1245 ////////////////////////////////////////////////////////////////////////
1248 public override bool Equals(Object value)
1250 if (Object.ReferenceEquals(this, value))
1253 CultureInfo that = value as CultureInfo;
1257 // using CompareInfo to verify the data passed through the constructor
1258 // CultureInfo(String cultureName, String textAndCompareCultureName)
1260 return (this.Name.Equals(that.Name) && this.CompareInfo.Equals(that.CompareInfo));
1267 ////////////////////////////////////////////////////////////////////////
1271 // Implements Object.GetHashCode(). Returns the hash code for the
1272 // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
1273 // and B where A.Equals(B) is true.
1275 ////////////////////////////////////////////////////////////////////////
1277 public override int GetHashCode()
1279 return (this.Name.GetHashCode() + this.CompareInfo.GetHashCode());
1283 ////////////////////////////////////////////////////////////////////////
1287 // Implements Object.ToString(). Returns the name of the CultureInfo,
1288 // eg. "de-DE_phoneb", "en-US", or "fj-FJ".
1290 ////////////////////////////////////////////////////////////////////////
1293 public override String ToString()
1295 Contract.Ensures(Contract.Result<String>() != null);
1297 Contract.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
1302 public virtual Object GetFormat(Type formatType) {
1303 if (formatType == typeof(NumberFormatInfo)) {
1304 return (NumberFormat);
1306 if (formatType == typeof(DateTimeFormatInfo)) {
1307 return (DateTimeFormat);
1312 public virtual bool IsNeutralCulture {
1314 return this.m_cultureData.IsNeutralCulture;
1318 #if !FEATURE_CORECLR
1319 [System.Runtime.InteropServices.ComVisible(false)]
1320 public CultureTypes CultureTypes
1324 CultureTypes types = 0;
1326 if (m_cultureData.IsNeutralCulture)
1327 types |= CultureTypes.NeutralCultures;
1329 types |= CultureTypes.SpecificCultures;
1331 types |= m_cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0;
1333 // Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
1334 #pragma warning disable 618
1335 types |= m_cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0;
1337 #pragma warning restore 618
1338 types |= m_cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0;
1339 types |= m_cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0;
1346 public virtual NumberFormatInfo NumberFormat {
1349 Contract.Ensures(Contract.Result<NumberFormatInfo>() != null);
1351 if (numInfo == null) {
1352 NumberFormatInfo temp = new NumberFormatInfo(this.m_cultureData);
1353 temp.isReadOnly = m_isReadOnly;
1359 if (value == null) {
1360 throw new ArgumentNullException("value",
1361 Environment.GetResourceString("ArgumentNull_Obj"));
1363 Contract.EndContractBlock();
1369 ////////////////////////////////////////////////////////////////////////
1371 // GetDateTimeFormatInfo
1373 // Create a DateTimeFormatInfo, and fill in the properties according to
1376 ////////////////////////////////////////////////////////////////////////
1379 public virtual DateTimeFormatInfo DateTimeFormat {
1381 Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
1383 if (dateTimeInfo == null) {
1384 // Change the calendar of DTFI to the specified calendar of this CultureInfo.
1385 DateTimeFormatInfo temp = new DateTimeFormatInfo(
1386 this.m_cultureData, this.Calendar);
1387 temp.m_isReadOnly = m_isReadOnly;
1388 System.Threading.Thread.MemoryBarrier();
1389 dateTimeInfo = temp;
1391 return (dateTimeInfo);
1395 if (value == null) {
1396 throw new ArgumentNullException("value",
1397 Environment.GetResourceString("ArgumentNull_Obj"));
1399 Contract.EndContractBlock();
1401 dateTimeInfo = value;
1407 public void ClearCachedData() {
1408 s_userDefaultUICulture = null;
1409 s_userDefaultCulture = null;
1411 RegionInfo.s_currentRegionInfo = null;
1412 #if !FEATURE_CORECLR // System.TimeZone does not exist in CoreCLR
1413 TimeZone.ResetTimeZone();
1414 #endif // FEATURE_CORECLR
1415 TimeZoneInfo.ClearCachedData();
1416 // Delete the cached cultures.
1417 s_LcidCachedCultures = null;
1418 s_NameCachedCultures = null;
1420 CultureData.ClearCachedData();
1423 /*=================================GetCalendarInstance==========================
1424 **Action: Map a Win32 CALID to an instance of supported calendar.
1425 **Returns: An instance of calendar.
1426 **Arguments: calType The Win32 CALID
1428 ** Shouldn't throw exception since the calType value is from our data table or from Win32 registry.
1429 ** If we are in trouble (like getting a weird value from Win32 registry), just return the GregorianCalendar.
1430 ============================================================================*/
1431 internal static Calendar GetCalendarInstance(int calType) {
1432 if (calType==Calendar.CAL_GREGORIAN) {
1433 return (new GregorianCalendar());
1435 return GetCalendarInstanceRare(calType);
1438 //This function exists as a shortcut to prevent us from loading all of the non-gregorian
1439 //calendars unless they're required.
1440 internal static Calendar GetCalendarInstanceRare(int calType) {
1441 Contract.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
1444 case Calendar.CAL_GREGORIAN_US: // Gregorian (U.S.) calendar
1445 case Calendar.CAL_GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar
1446 case Calendar.CAL_GREGORIAN_ARABIC: // Gregorian Arabic calendar
1447 case Calendar.CAL_GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar
1448 case Calendar.CAL_GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar
1449 return (new GregorianCalendar((GregorianCalendarTypes)calType));
1450 case Calendar.CAL_TAIWAN: // Taiwan Era calendar
1451 return (new TaiwanCalendar());
1452 case Calendar.CAL_JAPAN: // Japanese Emperor Era calendar
1453 return (new JapaneseCalendar());
1454 case Calendar.CAL_KOREA: // Korean Tangun Era calendar
1455 return (new KoreanCalendar());
1456 case Calendar.CAL_THAI: // Thai calendar
1457 return (new ThaiBuddhistCalendar());
1458 case Calendar.CAL_HIJRI: // Hijri (Arabic Lunar) calendar
1459 return (new HijriCalendar());
1460 case Calendar.CAL_HEBREW: // Hebrew (Lunar) calendar
1461 return (new HebrewCalendar());
1462 case Calendar.CAL_UMALQURA:
1463 return (new UmAlQuraCalendar());
1464 case Calendar.CAL_PERSIAN:
1465 return (new PersianCalendar());
1466 case Calendar.CAL_CHINESELUNISOLAR:
1467 return (new ChineseLunisolarCalendar());
1468 case Calendar.CAL_JAPANESELUNISOLAR:
1469 return (new JapaneseLunisolarCalendar());
1470 case Calendar.CAL_KOREANLUNISOLAR:
1471 return (new KoreanLunisolarCalendar());
1472 case Calendar.CAL_TAIWANLUNISOLAR:
1473 return (new TaiwanLunisolarCalendar());
1475 return (new GregorianCalendar());
1479 /*=================================Calendar==========================
1480 **Action: Return/set the default calendar used by this culture.
1481 ** This value can be overridden by regional option if this is a current culture.
1485 ** ArgumentNull_Obj if the set value is null.
1486 ============================================================================*/
1489 public virtual Calendar Calendar {
1491 Contract.Ensures(Contract.Result<Calendar>() != null);
1492 if (calendar == null) {
1493 Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
1494 // Get the default calendar for this culture. Note that the value can be
1495 // from registry if this is a user default culture.
1496 Calendar newObj = this.m_cultureData.DefaultCalendar;
1498 System.Threading.Thread.MemoryBarrier();
1499 newObj.SetReadOnlyState(m_isReadOnly);
1506 /*=================================OptionCalendars==========================
1507 **Action: Return an array of the optional calendar for this culture.
1508 **Returns: an array of Calendar.
1511 ============================================================================*/
1514 public virtual Calendar[] OptionalCalendars {
1516 Contract.Ensures(Contract.Result<Calendar[]>() != null);
1519 // This property always returns a new copy of the calendar array.
1521 int[] calID = this.m_cultureData.CalendarIds;
1522 Calendar [] cals = new Calendar[calID.Length];
1523 for (int i = 0; i < cals.Length; i++) {
1524 cals[i] = GetCalendarInstance(calID[i]);
1531 public bool UseUserOverride {
1533 return (this.m_cultureData.UseUserOverride);
1537 #if !FEATURE_CORECLR
1538 [System.Security.SecuritySafeCritical] // auto-generated
1539 [System.Runtime.InteropServices.ComVisible(false)]
1540 public CultureInfo GetConsoleFallbackUICulture()
1542 Contract.Ensures(Contract.Result<CultureInfo>() != null);
1544 CultureInfo temp = m_consoleFallbackCulture;
1547 temp = CreateSpecificCulture(this.m_cultureData.SCONSOLEFALLBACKNAME);
1548 temp.m_isReadOnly = true;
1549 m_consoleFallbackCulture = temp;
1555 public virtual Object Clone()
1557 Contract.Ensures(Contract.Result<Object>() != null);
1559 CultureInfo ci = (CultureInfo)MemberwiseClone();
1560 ci.m_isReadOnly = false;
1562 //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless
1563 //they've already been allocated. If this is a derived type, we'll take a more generic codepath.
1566 if (this.dateTimeInfo != null)
1568 ci.dateTimeInfo = (DateTimeFormatInfo)this.dateTimeInfo.Clone();
1570 if (this.numInfo != null)
1572 ci.numInfo = (NumberFormatInfo)this.numInfo.Clone();
1578 ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone();
1579 ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone();
1582 if (textInfo != null)
1584 ci.textInfo = (TextInfo) textInfo.Clone();
1587 if (calendar != null)
1589 ci.calendar = (Calendar) calendar.Clone();
1596 public static CultureInfo ReadOnly(CultureInfo ci) {
1598 throw new ArgumentNullException("ci");
1600 Contract.Ensures(Contract.Result<CultureInfo>() != null);
1601 Contract.EndContractBlock();
1603 if (ci.IsReadOnly) {
1606 CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone());
1608 if (!ci.IsNeutralCulture)
1610 //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless
1611 //they've already been allocated. If this is a derived type, we'll take a more generic codepath.
1612 if (!ci.m_isInherited) {
1613 if (ci.dateTimeInfo != null) {
1614 newInfo.dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci.dateTimeInfo);
1616 if (ci.numInfo != null) {
1617 newInfo.numInfo = NumberFormatInfo.ReadOnly(ci.numInfo);
1621 newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat);
1622 newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat);
1626 if (ci.textInfo != null)
1628 newInfo.textInfo = TextInfo.ReadOnly(ci.textInfo);
1631 if (ci.calendar != null)
1633 newInfo.calendar = Calendar.ReadOnly(ci.calendar);
1636 // Don't set the read-only flag too early.
1637 // We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set.
1638 newInfo.m_isReadOnly = true;
1644 public bool IsReadOnly {
1646 return (m_isReadOnly);
1650 private void VerifyWritable() {
1652 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
1654 Contract.EndContractBlock();
1657 // For resource lookup, we consider a culture the invariant culture by name equality.
1658 // We perform this check frequently during resource lookup, so adding a property for
1659 // improved readability.
1660 internal bool HasInvariantCultureName
1662 get { return Name == CultureInfo.InvariantCulture.Name; }
1665 // Helper function both both overloads of GetCachedReadOnlyCulture. If lcid is 0, we use the name.
1666 // If lcid is -1, use the altName and create one of those special SQL cultures.
1667 internal static CultureInfo GetCultureInfoHelper(int lcid, string name, string altName)
1669 // There is a race condition in this code with the side effect that the second thread's value
1670 // clobbers the first in the dictionary. This is an acceptable race condition since the CultureInfo objects
1671 // are content equal (but not reference equal). Since we make no guarantees there, this race condition is
1673 // See code:Dictionary#DictionaryVersusHashtableThreadSafety for details on Dictionary versus
1674 // Hashtable thread safety.
1676 // retval is our return value.
1679 // Temporary hashtable for the names.
1680 Hashtable tempNameHT = s_NameCachedCultures;
1684 name = CultureData.AnsiToLower(name);
1687 if (altName != null)
1689 altName = CultureData.AnsiToLower(altName);
1692 // We expect the same result for both hashtables, but will test individually for added safety.
1693 if (tempNameHT == null)
1695 tempNameHT = Hashtable.Synchronized(new Hashtable());
1699 // If we are called by name, check if the object exists in the hashtable. If so, return it.
1702 retval = (CultureInfo)tempNameHT[name + '\xfffd' + altName];
1710 retval = (CultureInfo)tempNameHT[name];
1717 #if FEATURE_USE_LCID
1718 // Next, the Lcid table.
1719 Hashtable tempLcidHT = s_LcidCachedCultures;
1721 if (tempLcidHT == null)
1723 // Case insensitive is not an issue here, save the constructor call.
1724 tempLcidHT = Hashtable.Synchronized(new Hashtable());
1728 // If we were called by Lcid, check if the object exists in the table. If so, return it.
1731 retval = (CultureInfo) tempLcidHT[lcid];
1739 // We now have two temporary hashtables and the desired object was not found.
1740 // We'll construct it. We catch any exceptions from the constructor call and return null.
1746 // call the private constructor
1747 retval = new CultureInfo(name, altName);
1751 retval = new CultureInfo(name, false);
1755 #if FEATURE_USE_LCID
1756 retval = new CultureInfo(lcid, false);
1763 catch(ArgumentException)
1768 // Set it to read-only
1769 retval.m_isReadOnly = true;
1773 // This new culture will be added only to the name hash table.
1774 tempNameHT[name + '\xfffd' + altName] = retval;
1776 // when lcid == -1 then TextInfo object is already get created and we need to set it as read only.
1777 retval.TextInfo.SetReadOnlyState(true);
1781 // Remember our name (as constructed). Do NOT use alternate sort name versions because
1782 // we have internal state representing the sort. (So someone would get the wrong cached version)
1783 string newName = CultureData.AnsiToLower(retval.m_name);
1785 // We add this new culture info object to both tables.
1786 tempNameHT[newName] = retval;
1787 #if FEATURE_USE_LCID
1788 const int LCID_ZH_CHS_HANS = 0x0004;
1789 const int LCID_ZH_CHT_HANT = 0x7c04;
1791 if ((retval.LCID == LCID_ZH_CHS_HANS && newName == "zh-hans")
1792 || (retval.LCID == LCID_ZH_CHT_HANT && newName == "zh-hant"))
1794 // do nothing because we only want zh-CHS and zh-CHT to cache
1799 tempLcidHT[retval.LCID] = retval;
1805 #if FEATURE_USE_LCID
1806 // Copy the two hashtables to the corresponding member variables. This will potentially overwrite
1807 // new tables simultaneously created by a new thread, but maximizes thread safety.
1810 // Only when we modify the lcid hash table, is there a need to overwrite.
1811 s_LcidCachedCultures = tempLcidHT;
1815 s_NameCachedCultures = tempNameHT;
1817 // Finally, return our new CultureInfo object.
1821 #if FEATURE_USE_LCID
1822 // Gets a cached copy of the specified culture from an internal hashtable (or creates it
1823 // if not found). (LCID version)... use named version
1824 public static CultureInfo GetCultureInfo(int culture)
1826 // Must check for -1 now since the helper function uses the value to signal
1827 // the altCulture code path for SQL Server.
1828 // Also check for zero as this would fail trying to add as a key to the hash.
1830 throw new ArgumentOutOfRangeException("culture",
1831 Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
1833 Contract.Ensures(Contract.Result<CultureInfo>() != null);
1834 Contract.EndContractBlock();
1835 CultureInfo retval = GetCultureInfoHelper(culture, null, null);
1838 throw new CultureNotFoundException(
1839 "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported"));
1845 // Gets a cached copy of the specified culture from an internal hashtable (or creates it
1846 // if not found). (Named version)
1847 public static CultureInfo GetCultureInfo(string name)
1849 // Make sure we have a valid, non-zero length string as name
1852 throw new ArgumentNullException("name");
1854 Contract.Ensures(Contract.Result<CultureInfo>() != null);
1855 Contract.EndContractBlock();
1857 CultureInfo retval = GetCultureInfoHelper(0, name, null);
1860 throw new CultureNotFoundException(
1861 "name", name, Environment.GetResourceString("Argument_CultureNotSupported"));
1867 // Gets a cached copy of the specified culture from an internal hashtable (or creates it
1869 public static CultureInfo GetCultureInfo(string name, string altName)
1871 // Make sure we have a valid, non-zero length string as name
1874 throw new ArgumentNullException("name");
1877 if (null == altName)
1879 throw new ArgumentNullException("altName");
1881 Contract.Ensures(Contract.Result<CultureInfo>() != null);
1882 Contract.EndContractBlock();
1884 CultureInfo retval = GetCultureInfoHelper(-1, name, altName);
1887 throw new CultureNotFoundException("name or altName",
1889 CultureInfo.CurrentCulture,
1890 Environment.GetResourceString("Argument_OneOfCulturesNotSupported"),
1898 // This function is deprecated, we don't like it
1899 public static CultureInfo GetCultureInfoByIetfLanguageTag(string name)
1901 Contract.Ensures(Contract.Result<CultureInfo>() != null);
1903 // Disallow old zh-CHT/zh-CHS names
1904 if (name == "zh-CHT" || name == "zh-CHS")
1906 throw new CultureNotFoundException(
1908 String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
1912 CultureInfo ci = GetCultureInfo(name);
1914 // Disallow alt sorts and es-es_TS
1915 if (ci.LCID > 0xffff || ci.LCID == 0x040a)
1917 throw new CultureNotFoundException(
1919 String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
1926 private static volatile bool s_isTaiwanSku;
1927 private static volatile bool s_haveIsTaiwanSku;
1928 internal static bool IsTaiwanSku
1932 if (!s_haveIsTaiwanSku)
1934 s_isTaiwanSku = (GetSystemDefaultUILanguage() == "zh-TW");
1935 s_haveIsTaiwanSku = true;
1937 return (bool)s_isTaiwanSku;
1945 // Get Locale Info Ex calls. So we don't have to muck with the different int/string return types we declared two of these:
1946 [System.Security.SecurityCritical] // auto-generated
1947 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1948 internal static extern String nativeGetLocaleInfoEx(String localeName, uint field);
1950 [System.Security.SecuritySafeCritical] // auto-generated
1951 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1952 internal static extern int nativeGetLocaleInfoExInt(String localeName, uint field);
1954 [System.Security.SecurityCritical] // auto-generated
1955 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1956 internal static extern bool nativeSetThreadLocale(String localeName);
1958 [System.Security.SecurityCritical]
1959 private static String GetDefaultLocaleName(int localeType)
1961 Contract.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
1963 string localeName = null;
1964 if(InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName)))
1968 return string.Empty;
1971 // Get the default locale name
1972 [System.Security.SecurityCritical] // auto-generated
1973 [SuppressUnmanagedCodeSecurity]
1974 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
1975 [return: MarshalAs(UnmanagedType.Bool)]
1976 private static extern bool InternalGetDefaultLocaleName(int localetype, StringHandleOnStack localeString);
1978 [System.Security.SecuritySafeCritical] // auto-generated
1979 private static String GetUserDefaultUILanguage()
1981 string userDefaultUiLanguage = null;
1982 if(InternalGetUserDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref userDefaultUiLanguage)))
1984 return userDefaultUiLanguage;
1986 return String.Empty;
1989 // Get the user's default UI language, return locale name
1990 [System.Security.SecurityCritical] // auto-generated
1991 [SuppressUnmanagedCodeSecurity]
1992 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
1993 [return: MarshalAs(UnmanagedType.Bool)]
1994 private static extern bool InternalGetUserDefaultUILanguage(StringHandleOnStack userDefaultUiLanguage);
1996 [System.Security.SecuritySafeCritical] // auto-generated
1997 private static String GetSystemDefaultUILanguage()
1999 string systemDefaultUiLanguage = null;
2000 if(InternalGetSystemDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref systemDefaultUiLanguage)))
2002 return systemDefaultUiLanguage;
2004 return String.Empty;
2008 [System.Security.SecurityCritical] // auto-generated
2009 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2010 [SuppressUnmanagedCodeSecurity]
2011 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2012 [return: MarshalAs(UnmanagedType.Bool)]
2013 private static extern bool InternalGetSystemDefaultUILanguage(StringHandleOnStack systemDefaultUiLanguage);
2015 // Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
2017 [System.Security.SecurityCritical] // auto-generated
2018 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2019 internal static extern String[] nativeGetResourceFallbackArray();