Expose missing Global/Encoding APIs in coreclr and remove empty stubs
[platform/upstream/coreclr.git] / src / mscorlib / src / System / Globalization / CultureInfo.cs
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.
4
5 ////////////////////////////////////////////////////////////////////////////
6 //
7 //
8 //
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.
14 //
15 //
16 //
17 //  !!!! NOTE WHEN CHANGING THIS CLASS !!!!
18 //
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.
26 //
27 ////////////////////////////////////////////////////////////////////////////
28
29 namespace System.Globalization {
30     using System;
31     using System.Security;
32     using System.Threading;
33     using System.Collections;
34     using System.Runtime;
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;
44
45     [Serializable]
46     [System.Runtime.InteropServices.ComVisible(true)]
47     public partial class CultureInfo : ICloneable, IFormatProvider {
48         //--------------------------------------------------------------------//
49         //                        Internal Information                        //
50         //--------------------------------------------------------------------//
51
52         //--------------------------------------------------------------------//
53         // Data members to be serialized:
54         //--------------------------------------------------------------------//
55
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
59
60         // WARNING
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
65         // WARNING
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)
70 #if !FEATURE_CORECLR
71         [NonSerialized]internal RegionInfo regionInfo;
72 #endif
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)
80         //
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.
84         //
85         [NonSerialized]internal CultureData m_cultureData;
86         
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
92 #if !FEATURE_CORECLR
93         [NonSerialized]private CultureInfo m_consoleFallbackCulture;
94 #endif // !FEATURE_CORECLR
95
96         // Names are confusing.  Here are 3 names we have:
97         //
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)
102         //      en              en              
103         //
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
106
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;
111
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;
115
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;
120
121
122         //--------------------------------------------------------------------//
123         //
124         // Static data members
125         //
126         //--------------------------------------------------------------------//
127
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;
130
131         //
132         // All of the following will be created on demand.
133         //
134
135         //The Invariant culture;
136         private static volatile CultureInfo s_InvariantCultureInfo;
137
138         //The culture used in the user interface. This is mostly used to load correct localized resources.
139         private static volatile CultureInfo s_userDefaultUICulture;
140
141         //This is the UI culture used to install the OS.
142         private static volatile CultureInfo s_InstalledUICultureInfo;
143
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;
147
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;
152
153 #if FEATURE_APPX
154         // When running under AppX, we use this to get some information about the language list
155         [SecurityCritical]
156         private static volatile WindowsRuntimeResourceManagerBase s_WindowsRuntimeResourceManager;
157
158         [ThreadStatic]
159         private static bool ts_IsDoingAppXCultureInfoLookup;
160 #endif
161
162         //The parent culture.
163         [NonSerialized]private CultureInfo m_parent;
164
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;
174
175         //
176         // The CultureData  instance that reads the data provided by our CultureData class.
177         //
178         //Using a field initializer rather than a static constructor so that the whole class can be lazy
179         //init.
180         private static readonly bool init = Init();
181         private static bool Init()
182         {
183
184             if (s_InvariantCultureInfo == null) 
185             {
186                 CultureInfo temp = new CultureInfo("", false);
187                 temp.m_isReadOnly = true;
188                 s_InvariantCultureInfo = temp;
189             }
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;
194
195             s_userDefaultCulture = InitUserDefaultCulture();
196             s_userDefaultUICulture = InitUserDefaultUICulture();
197             return true;
198         }
199
200         [System.Security.SecuritySafeCritical]  // auto-generated
201         static CultureInfo InitUserDefaultCulture()
202         {
203             String strDefault = GetDefaultLocaleName(LOCALE_USER_DEFAULT);
204             if (strDefault == null)
205             {
206                 strDefault = GetDefaultLocaleName(LOCALE_SYSTEM_DEFAULT);
207
208                 if (strDefault == null)
209                 {
210                     // If system default doesn't work, keep using the invariant
211                     return (CultureInfo.InvariantCulture);
212                 }
213             }
214             CultureInfo temp = GetCultureByName(strDefault, true);
215
216             temp.m_isReadOnly = true;
217
218             return (temp);
219         }
220
221         static CultureInfo InitUserDefaultUICulture()
222         {
223             String strDefault = GetUserDefaultUILanguage();
224
225             // In most of cases, UserDefaultCulture == UserDefaultUICulture, so we should use the same instance if possible.
226             if (strDefault == UserDefaultCulture.Name)
227             {
228                 return (UserDefaultCulture);
229             }
230
231             CultureInfo temp = GetCultureByName( strDefault, true);
232
233             if (temp == null)
234             {
235                 return (CultureInfo.InvariantCulture);
236             }
237
238             temp.m_isReadOnly = true;
239
240             return (temp);
241         }
242
243 #if FEATURE_APPX
244         [SecuritySafeCritical]
245         internal static CultureInfo GetCultureInfoForUserPreferredLanguageInAppX()
246         {
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)
254             {
255                 return null;
256             }
257
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)
265             {
266                 return null;
267             }
268
269             CultureInfo toReturn = null;
270
271             try 
272             {
273                 ts_IsDoingAppXCultureInfoLookup = true;
274
275                 if(s_WindowsRuntimeResourceManager == null)
276                 {
277                     s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
278                 }
279
280                 toReturn = s_WindowsRuntimeResourceManager.GlobalResourceContextBestFitCultureInfo;
281             } 
282             finally 
283             {
284                ts_IsDoingAppXCultureInfoLookup = false;
285             }
286  
287             return toReturn;
288         }
289
290         [SecuritySafeCritical]
291         internal static bool SetCultureInfoForUserPreferredLanguageInAppX(CultureInfo ci)
292         {
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)
300             {
301                 return false;
302             }
303
304             if (s_WindowsRuntimeResourceManager == null)
305             {
306                 s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
307             }
308
309             return s_WindowsRuntimeResourceManager.SetGlobalResourceContextDefaultCulture(ci);
310         }
311 #endif
312
313         ////////////////////////////////////////////////////////////////////////
314         //
315         //  CultureInfo Constructors
316         //
317         ////////////////////////////////////////////////////////////////////////
318
319
320         public CultureInfo(String name) : this(name, true) {
321         }
322
323
324         public CultureInfo(String name, bool useUserOverride) {
325             if (name==null) {
326                 throw new ArgumentNullException("name",
327                     Environment.GetResourceString("ArgumentNull_String"));
328             }
329             Contract.EndContractBlock();
330
331             // Get our data providing record
332             this.m_cultureData = CultureData.GetCultureData(name, useUserOverride);
333
334             if (this.m_cultureData == null) {
335                 throw new CultureNotFoundException("name", name, Environment.GetResourceString("Argument_CultureNotSupported"));
336             }
337
338             this.m_name = this.m_cultureData.CultureName;
339             this.m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
340         }
341
342
343 #if FEATURE_USE_LCID
344         public CultureInfo(int culture) : this(culture, true) {
345         }
346
347         public CultureInfo(int culture, bool useUserOverride) {
348             // We don't check for other invalid LCIDS here...
349             if (culture < 0) {
350                 throw new ArgumentOutOfRangeException("culture",
351                     Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
352             }
353             Contract.EndContractBlock();
354
355             InitializeFromCultureId(culture, useUserOverride);
356         }
357
358         private void InitializeFromCultureId(int culture, bool useUserOverride)
359         {
360             switch (culture)
361             {
362                 case LOCALE_CUSTOM_DEFAULT:
363                 case LOCALE_SYSTEM_DEFAULT:
364                 case LOCALE_NEUTRAL:
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"));
371
372                 default:
373                     // Now see if this LCID is supported in the system default CultureData  table.
374                     this.m_cultureData = CultureData.GetCultureData(culture, useUserOverride);
375                     break;
376             }
377             this.m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
378             this.m_name = this.m_cultureData.CultureName;
379         }
380 #endif // FEATURE_USE_LCID
381
382         //
383         // CheckDomainSafetyObject throw if the object is customized object which cannot be attached to 
384         // other object (like CultureInfo or DateTimeFormatInfo).
385         //
386
387         internal static void CheckDomainSafetyObject(Object obj, Object container)
388         {
389             if (obj.GetType().Assembly != typeof(System.Globalization.CultureInfo).Assembly) {
390                 
391                 throw new InvalidOperationException(
392                             String.Format(
393                                 CultureInfo.CurrentCulture, 
394                                 Environment.GetResourceString("InvalidOperation_SubclassedObject"), 
395                                 obj.GetType(),
396                                 container.GetType()));
397             }
398             Contract.EndContractBlock();
399         }
400
401 #region Serialization
402         // We need to store the override from the culture data record.
403         private bool    m_useUserOverride;
404
405         [OnDeserialized]
406         private void OnDeserialized(StreamingContext ctx)
407         {
408 #if FEATURE_USE_LCID
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))
415             {
416                 Contract.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
417                 InitializeFromCultureId(cultureID, m_useUserOverride);
418             }
419             else
420             {
421 #endif
422                 Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
423
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"));
428                     
429 #if FEATURE_USE_LCID
430             }
431 #endif
432             m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
433
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)
437             {
438                 if (textInfo != null)
439                 {
440                     CheckDomainSafetyObject(textInfo, this);
441                 }
442                 
443                 if (compareInfo != null)
444                 {
445                     CheckDomainSafetyObject(compareInfo, this);
446                 }
447             }
448         }
449
450 #if FEATURE_USE_LCID
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:
454         //
455         //  +------------------------+-------+--------------------------------+
456         //  |        Reserved        |Sort ID|           Language ID          |
457         //  +------------------------+-------+--------------------------------+
458         //  31                     20 19   16 15                             0   bit
459         private const int LOCALE_SORTID_MASK = 0x000f0000;
460
461         static private bool IsAlternateSortLcid(int lcid)
462         {
463             if(lcid == LOCALE_TRADITIONAL_SPANISH)
464             {
465                 return true;
466             }
467
468             return (lcid & LOCALE_SORTID_MASK) != 0;
469         }
470 #endif
471
472         [OnSerializing]
473         private void OnSerializing(StreamingContext ctx)
474         {
475             this.m_name              = this.m_cultureData.CultureName;
476             this.m_useUserOverride   = this.m_cultureData.UseUserOverride;
477 #if FEATURE_USE_LCID
478             // for compatibility with v2 serialize cultureID
479             this.cultureID = this.m_cultureData.ILANGUAGE;
480 #endif
481         }
482 #endregion Serialization
483
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 {
488             get {
489                 Contract.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
490                 return m_isSafeCrossDomain;
491             }
492         }
493
494         internal int CreatedDomainID {
495             get {
496                 Contract.Assert(m_createdDomainID != 0,  "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
497                 return m_createdDomainID;
498             }
499         }
500
501         internal void StartCrossDomainTracking() {
502         
503             // If we have decided about cross domain safety of this instance, we are done
504             if (m_createdDomainID != 0)
505                 return;
506
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())
510             {
511                 m_isSafeCrossDomain = true;
512             }
513
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();
518         }
519 #endif // FEATURE_LEAK_CULTURE_INFO
520
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()
525         {
526             bool isSafe = false;
527             if (this.GetType() == typeof(System.Globalization.CultureInfo))
528             {
529                 isSafe = true;
530             }
531             return isSafe;
532         }
533
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)
541         {
542             if (cultureName==null) {
543                 throw new ArgumentNullException("cultureName",
544                     Environment.GetResourceString("ArgumentNull_String"));
545             }
546             Contract.EndContractBlock();
547
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"));
552             
553             this.m_name = this.m_cultureData.CultureName;            
554
555             CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName);
556             this.compareInfo = altCulture.CompareInfo;
557             this.textInfo = altCulture.TextInfo;
558         }
559
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)
563         {           
564             // Try to get our culture
565             try
566             {
567                 return userOverride ? new CultureInfo(name) : CultureInfo.GetCultureInfo(name);
568             }
569             catch (ArgumentException)
570             {
571             }
572
573             return null;
574         }
575
576         //
577         // Return a specific culture.  A tad irrelevent now since we always return valid data
578         // for neutral locales.
579         //
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
583         //
584         public static CultureInfo CreateSpecificCulture(String name) {
585             Contract.Ensures(Contract.Result<CultureInfo>() != null);
586
587             CultureInfo culture;
588
589             try {
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.
595
596                 int idx;
597
598                 culture = null;
599                 for(idx = 0; idx < name.Length; idx++) {
600                     if('-' == name[idx]) {
601                         try {
602                             culture = new CultureInfo(name.Substring(0, idx));
603                             break;
604                         } catch(ArgumentException) {
605                             // throw the original exception so the name in the string will be right
606                             throw;
607                         }
608                     }
609                 }
610
611                 if(null == culture) {
612                     // nothing to save here; throw the original exception
613                     throw;
614                 }
615             }
616
617             //In the most common case, they've given us a specific culture, so we'll just return that.
618             if (!(culture.IsNeutralCulture)) {
619                 return culture;
620             }
621
622             return (new CultureInfo(culture.m_cultureData.SSPECIFICCULTURE));
623         }
624
625         internal static bool VerifyCultureName(String cultureName, bool throwException) 
626         {
627             // This function is used by ResourceManager.GetResourceFileName(). 
628             // ResourceManager searches for resource using CultureInfo.Name,
629             // so we should check against CultureInfo.Name.
630
631             for (int i=0; i<cultureName.Length; i++) {
632                 char c = cultureName[i];
633
634                 if (Char.IsLetterOrDigit(c) || c=='-' || c=='_') {
635                     continue;
636                 }
637                 if (throwException) {
638                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidResourceCultureName", cultureName));
639                 }
640                 return false;
641             }
642             return true;
643             
644         }
645
646         internal static bool VerifyCultureName(CultureInfo culture, bool throwException) {
647             Contract.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
648
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) {
652                 return true;
653             }
654
655             return VerifyCultureName(culture.Name, throwException);
656
657         }
658
659         ////////////////////////////////////////////////////////////////////////
660         //
661         //  CurrentCulture
662         //
663         //  This instance provides methods based on the current user settings.
664         //  These settings are volatile and may change over the lifetime of the
665         //  thread.
666         //
667         ////////////////////////////////////////////////////////////////////////
668
669
670         public static CultureInfo CurrentCulture
671         {
672             get {
673                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
674
675 #if !FEATURE_CORECLR
676                 return Thread.CurrentThread.CurrentCulture;
677 #else
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.
687 #if FEATURE_APPX
688                 if(AppDomain.IsAppXModel()) {
689                     CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
690                     if (culture != null)
691                         return culture;
692                 }
693 #endif
694                 return Thread.m_CurrentCulture ??
695                     s_DefaultThreadCurrentCulture ??
696                     s_userDefaultCulture ??
697                     UserDefaultCulture;
698 #endif
699             }
700
701             set {
702 #if FEATURE_APPX
703                     if (value == null) {
704                         throw new ArgumentNullException("value");
705                     }                    
706
707                     if (AppDomain.IsAppXModel()) {
708                         if (SetCultureInfoForUserPreferredLanguageInAppX(value)) {
709                             // successfully set the culture, otherwise fallback to legacy path
710                             return; 
711                         }
712                     }
713 #endif
714                     Thread.CurrentThread.CurrentCulture = value;
715             }
716         }
717
718         //
719         // This is the equivalence of the Win32 GetUserDefaultLCID()
720         //
721         internal static CultureInfo UserDefaultCulture {
722             get
723             {
724                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
725
726                 CultureInfo temp = s_userDefaultCulture;
727                 if (temp == null)
728                 {
729                     //
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.
733                     //
734                     
735                     s_userDefaultCulture = CultureInfo.InvariantCulture;
736                     temp = InitUserDefaultCulture();
737                     s_userDefaultCulture = temp;
738                 }
739                 return (temp);
740             }
741         }
742
743         //
744         //  This is the equivalence of the Win32 GetUserDefaultUILanguage()
745         //
746         internal static CultureInfo UserDefaultUICulture {
747             get {
748                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
749
750                 CultureInfo temp = s_userDefaultUICulture;
751                 if (temp == null) 
752                 {
753                     //
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.
757                     //
758                     
759                     s_userDefaultUICulture = CultureInfo.InvariantCulture;
760                     
761                     temp = InitUserDefaultUICulture();
762                     s_userDefaultUICulture = temp;
763                 }
764                 return (temp);
765             }
766         }
767
768
769         public static CultureInfo CurrentUICulture {
770             get {
771                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
772
773 #if !FEATURE_CORECLR
774                 return Thread.CurrentThread.CurrentUICulture;
775 #else
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.
785 #if FEATURE_APPX
786                 if(AppDomain.IsAppXModel()) {
787                     CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
788                     if (culture != null)
789                         return culture;
790                 }
791 #endif
792                 return Thread.m_CurrentUICulture ??
793                     s_DefaultThreadCurrentUICulture ??
794                     s_userDefaultUICulture ??
795                     UserDefaultUICulture;
796 #endif
797             }
798
799             set {
800 #if FEATURE_APPX
801                     if (value == null) {
802                         throw new ArgumentNullException("value");
803                     }                    
804
805                     if (AppDomain.IsAppXModel()) {
806                         if (SetCultureInfoForUserPreferredLanguageInAppX(value)) {
807                             // successfully set the culture, otherwise fallback to legacy path
808                             return; 
809                         }
810                     }
811 #endif
812                     Thread.CurrentThread.CurrentUICulture = value;
813             }
814         }
815
816
817         //
818         // This is the equivalence of the Win32 GetSystemDefaultUILanguage()
819         //
820         public static CultureInfo InstalledUICulture {
821             get {
822                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
823
824                 CultureInfo temp = s_InstalledUICultureInfo;
825                 if (temp == null) {
826                     String strDefault = GetSystemDefaultUILanguage();
827                     temp = GetCultureByName(strDefault, true);
828
829                     if (temp == null)
830                     {
831                         temp = InvariantCulture;
832                     }
833
834                     temp.m_isReadOnly = true;
835                     s_InstalledUICultureInfo = temp;
836                 }
837                 return (temp);
838             }
839         }
840
841         public static CultureInfo DefaultThreadCurrentCulture {
842             get {
843                 return s_DefaultThreadCurrentCulture;
844             }
845
846             [System.Security.SecuritySafeCritical]  // auto-generated
847 #pragma warning disable 618
848             [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
849 #pragma warning restore 618
850             set {
851
852                 // If you add pre-conditions to this method, check to see if you also need to 
853                 // add them to Thread.CurrentCulture.set.
854
855                 s_DefaultThreadCurrentCulture = value;
856             }
857         }
858
859         public static CultureInfo DefaultThreadCurrentUICulture {
860             get {
861                 return s_DefaultThreadCurrentUICulture;
862             }
863
864             [System.Security.SecuritySafeCritical]  // auto-generated
865 #pragma warning disable 618
866             [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
867 #pragma warning restore 618
868             set {
869
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.
872
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.
875
876                 if (value != null) 
877                 {                   
878                     CultureInfo.VerifyCultureName(value, true);
879                 }
880
881                 s_DefaultThreadCurrentUICulture = value;
882             }
883         }
884
885         ////////////////////////////////////////////////////////////////////////
886         //
887         //  InvariantCulture
888         //
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
894         //  culture info.
895         //
896         ////////////////////////////////////////////////////////////////////////
897
898
899         public static CultureInfo InvariantCulture {
900             [Pure]
901             get {
902                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
903                 return (s_InvariantCultureInfo);
904             }
905         }
906
907
908         ////////////////////////////////////////////////////////////////////////
909         //
910         //  Parent
911         //
912         //  Return the parent CultureInfo for the current instance.
913         //
914         ////////////////////////////////////////////////////////////////////////
915
916         public virtual CultureInfo Parent
917         {
918             [System.Security.SecuritySafeCritical]  // auto-generated
919             get
920             {
921                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
922
923                 if (null == m_parent)
924                 {
925                     try
926                     {
927                         string parentName = this.m_cultureData.SPARENT;
928
929                         if (String.IsNullOrEmpty(parentName))
930                         {
931                             m_parent = InvariantCulture;
932                         }
933                         else
934                         {
935                             m_parent = new CultureInfo(parentName, this.m_cultureData.UseUserOverride);
936                         }
937                     }
938                     catch (ArgumentException)
939                     {
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;
944                     }
945                 }
946                 return m_parent;
947             }
948         }
949
950         ////////////////////////////////////////////////////////////////////////
951         //
952         //  LCID
953         //
954         //  Returns a properly formed culture identifier for the current
955         //  culture info.
956         //
957         ////////////////////////////////////////////////////////////////////////
958
959 #if FEATURE_USE_LCID
960         public virtual int LCID {
961             get {
962                 return (this.m_cultureData.ILANGUAGE);
963             }
964         }
965 #endif
966
967         ////////////////////////////////////////////////////////////////////////
968         //
969         //  BaseInputLanguage
970         //
971         //  Essentially an LCID, though one that may be different than LCID in the case
972         //  of a customized culture (LCID == LOCALE_CUSTOM_UNSPECIFIED).
973         //
974         ////////////////////////////////////////////////////////////////////////
975 #if FEATURE_USE_LCID
976         [System.Runtime.InteropServices.ComVisible(false)]
977         public virtual int KeyboardLayoutId
978         {
979             get
980             {
981                 int keyId = this.m_cultureData.IINPUTLANGUAGEHANDLE;
982
983                 // Not a customized culture, return the default Keyboard layout ID, which is the same as the language ID.
984                 return (keyId);
985             }
986         }
987 #endif
988
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)
994             {
995                 types |= CultureTypes.ReplacementCultures;
996             }
997             return (CultureData.GetCultures(types));
998         }
999
1000         ////////////////////////////////////////////////////////////////////////
1001         //
1002         //  Name
1003         //
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.
1006         //
1007         ////////////////////////////////////////////////////////////////////////
1008         public virtual String Name {
1009             get {
1010                 Contract.Ensures(Contract.Result<String>() != null);
1011
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;
1017                     }
1018                 }
1019                 return this.m_nonSortName;
1020             }
1021         }
1022
1023         // This one has the sort information (ie: de-DE_phoneb)
1024         internal String SortName
1025         {
1026             get
1027             {
1028                 if (this.m_sortName == null)
1029                 {
1030                     this.m_sortName = this.m_cultureData.SCOMPAREINFO;
1031                 }
1032
1033                 return this.m_sortName;
1034             }
1035         }
1036
1037 #if !FEATURE_CORECLR
1038         [System.Runtime.InteropServices.ComVisible(false)]
1039         public String IetfLanguageTag
1040         {
1041             get
1042             {
1043                 Contract.Ensures(Contract.Result<String>() != null);
1044
1045                 // special case the compatibility cultures
1046                 switch (this.Name)
1047                 {
1048                     case "zh-CHT":
1049                         return "zh-Hant";
1050                     case "zh-CHS":
1051                         return "zh-Hans";
1052                     default:
1053                         return this.Name;
1054                 }
1055             }
1056         }
1057 #endif
1058
1059         ////////////////////////////////////////////////////////////////////////
1060         //
1061         //  DisplayName
1062         //
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.
1066         //
1067         ////////////////////////////////////////////////////////////////////////
1068         public virtual String DisplayName
1069         {
1070             [System.Security.SecuritySafeCritical]  // auto-generated
1071             get
1072             {
1073                 Contract.Ensures(Contract.Result<String>() != null);
1074                 Contract.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
1075
1076                 return m_cultureData.SLOCALIZEDDISPLAYNAME;
1077             }
1078         }
1079
1080         ////////////////////////////////////////////////////////////////////////
1081         //
1082         //  GetNativeName
1083         //
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.
1087         //
1088         ////////////////////////////////////////////////////////////////////////
1089         public virtual String NativeName {
1090             [System.Security.SecuritySafeCritical]  // auto-generated
1091             get {
1092                 Contract.Ensures(Contract.Result<String>() != null);
1093                 return (this.m_cultureData.SNATIVEDISPLAYNAME);
1094             }
1095         }
1096
1097         ////////////////////////////////////////////////////////////////////////
1098         //
1099         //  GetEnglishName
1100         //
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.
1104         //
1105         ////////////////////////////////////////////////////////////////////////
1106         public virtual String EnglishName {
1107             [System.Security.SecuritySafeCritical]  // auto-generated
1108             get {
1109                 Contract.Ensures(Contract.Result<String>() != null);
1110                 return (this.m_cultureData.SENGDISPLAYNAME);
1111             }
1112         }
1113       
1114         // ie: en
1115         public virtual String TwoLetterISOLanguageName {
1116             [System.Security.SecuritySafeCritical]  // auto-generated
1117             get {
1118                 Contract.Ensures(Contract.Result<String>() != null);
1119                 return (this.m_cultureData.SISO639LANGNAME);
1120             }
1121         }
1122
1123         // ie: eng
1124         public virtual String ThreeLetterISOLanguageName {
1125             [System.Security.SecuritySafeCritical]  // auto-generated
1126             get {
1127                 Contract.Ensures(Contract.Result<String>() != null);
1128                 return (this.m_cultureData.SISO639LANGNAME2);
1129             }
1130         }
1131
1132         ////////////////////////////////////////////////////////////////////////
1133         //
1134         //  ThreeLetterWindowsLanguageName
1135         //
1136         //  Returns the 3 letter windows language name for the current instance.  eg: "ENU"
1137         //  The ISO names are much preferred
1138         //
1139         ////////////////////////////////////////////////////////////////////////
1140         public virtual String ThreeLetterWindowsLanguageName {
1141             [System.Security.SecuritySafeCritical]  // auto-generated
1142             get {
1143                 Contract.Ensures(Contract.Result<String>() != null);
1144                 return (this.m_cultureData.SABBREVLANGNAME);
1145             }
1146         }
1147
1148         ////////////////////////////////////////////////////////////////////////
1149         //
1150         //  CompareInfo               Read-Only Property
1151         //
1152         //  Gets the CompareInfo for this culture.
1153         //
1154         ////////////////////////////////////////////////////////////////////////
1155         public virtual CompareInfo CompareInfo
1156         {
1157             get
1158             {
1159                 Contract.Ensures(Contract.Result<CompareInfo>() != null);
1160
1161                 if (this.compareInfo == null)
1162                 {
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)
1169                     {
1170                         this.compareInfo = temp;
1171                     }
1172                     else
1173                     {
1174                         return temp;
1175                     }
1176                 }
1177                 return (compareInfo);
1178             }
1179         }
1180
1181 #if !FEATURE_CORECLR
1182         ////////////////////////////////////////////////////////////////////////
1183         //
1184         //  RegionInfo
1185         //
1186         //  Gets the RegionInfo for this culture.
1187         //
1188         ////////////////////////////////////////////////////////////////////////
1189         private RegionInfo Region
1190         {
1191             get
1192             {
1193                 if (regionInfo==null)
1194                 {
1195                     // Make a new regionInfo
1196                     RegionInfo tempRegionInfo = new RegionInfo(this.m_cultureData);
1197                     regionInfo = tempRegionInfo;
1198                 }
1199                 return (regionInfo);
1200             }
1201         }
1202 #endif // FEATURE_CORECLR
1203
1204
1205
1206         ////////////////////////////////////////////////////////////////////////
1207         //
1208         //  TextInfo
1209         //
1210         //  Gets the TextInfo for this culture.
1211         //
1212         ////////////////////////////////////////////////////////////////////////
1213
1214
1215         public virtual TextInfo TextInfo {
1216             get {
1217                 Contract.Ensures(Contract.Result<TextInfo>() != null);
1218
1219                 if (textInfo==null) 
1220                 {
1221                     // Make a new textInfo
1222                     TextInfo tempTextInfo = new TextInfo(this.m_cultureData);
1223                     tempTextInfo.SetReadOnlyState(m_isReadOnly);
1224
1225                     if (CompatibilitySwitches.IsCompatibilityBehaviorDefined)
1226                     {
1227                         textInfo = tempTextInfo;
1228                     }
1229                     else
1230                     {
1231                         return tempTextInfo;
1232                     }
1233                 }
1234                 return (textInfo);
1235             }
1236         }
1237
1238         ////////////////////////////////////////////////////////////////////////
1239         //
1240         //  Equals
1241         //
1242         //  Implements Object.Equals().  Returns a boolean indicating whether
1243         //  or not object refers to the same CultureInfo as the current instance.
1244         //
1245         ////////////////////////////////////////////////////////////////////////
1246
1247
1248         public override bool Equals(Object value)
1249         {
1250             if (Object.ReferenceEquals(this, value))
1251                 return true;
1252
1253             CultureInfo that = value as CultureInfo;
1254
1255             if (that != null)
1256             {
1257                 // using CompareInfo to verify the data passed through the constructor
1258                 // CultureInfo(String cultureName, String textAndCompareCultureName)
1259
1260                 return (this.Name.Equals(that.Name) && this.CompareInfo.Equals(that.CompareInfo));
1261             }
1262
1263             return (false);
1264         }
1265
1266
1267         ////////////////////////////////////////////////////////////////////////
1268         //
1269         //  GetHashCode
1270         //
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.
1274         //
1275         ////////////////////////////////////////////////////////////////////////
1276
1277         public override int GetHashCode()
1278         {
1279             return (this.Name.GetHashCode() + this.CompareInfo.GetHashCode());
1280         }
1281
1282
1283         ////////////////////////////////////////////////////////////////////////
1284         //
1285         //  ToString
1286         //
1287         //  Implements Object.ToString().  Returns the name of the CultureInfo,
1288         //  eg. "de-DE_phoneb", "en-US", or "fj-FJ".
1289         //
1290         ////////////////////////////////////////////////////////////////////////
1291
1292
1293         public override String ToString()
1294         {
1295             Contract.Ensures(Contract.Result<String>() != null);
1296
1297             Contract.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
1298             return m_name;
1299         }
1300
1301
1302         public virtual Object GetFormat(Type formatType) {
1303             if (formatType == typeof(NumberFormatInfo)) {
1304                 return (NumberFormat);
1305             }
1306             if (formatType == typeof(DateTimeFormatInfo)) {
1307                 return (DateTimeFormat);
1308             }
1309             return (null);
1310         }
1311
1312         public virtual bool IsNeutralCulture {
1313             get {
1314                 return this.m_cultureData.IsNeutralCulture;
1315             }
1316         }
1317
1318 #if !FEATURE_CORECLR
1319         [System.Runtime.InteropServices.ComVisible(false)]
1320         public CultureTypes CultureTypes
1321         {
1322             get
1323             {
1324                 CultureTypes types = 0;
1325
1326                 if (m_cultureData.IsNeutralCulture)
1327                     types |= CultureTypes.NeutralCultures;
1328                 else 
1329                     types |= CultureTypes.SpecificCultures;
1330
1331                 types |= m_cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0;
1332
1333 // Disable  warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
1334 #pragma warning disable 618
1335                 types |= m_cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0;
1336
1337 #pragma warning restore 618
1338                 types |= m_cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0;
1339                 types |= m_cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0;
1340
1341                 return types;
1342             }
1343         }
1344 #endif
1345
1346         public virtual NumberFormatInfo NumberFormat {
1347             get 
1348             {
1349                 Contract.Ensures(Contract.Result<NumberFormatInfo>() != null);
1350
1351                 if (numInfo == null) {
1352                     NumberFormatInfo temp = new NumberFormatInfo(this.m_cultureData);
1353                     temp.isReadOnly = m_isReadOnly;
1354                     numInfo = temp;
1355                 }
1356                 return (numInfo);
1357             }
1358             set {
1359                 if (value == null) {
1360                     throw new ArgumentNullException("value",
1361                         Environment.GetResourceString("ArgumentNull_Obj"));
1362                 }
1363                 Contract.EndContractBlock();
1364                 VerifyWritable();
1365                 numInfo = value;
1366             }
1367         }
1368
1369         ////////////////////////////////////////////////////////////////////////
1370         //
1371         // GetDateTimeFormatInfo
1372         //
1373         // Create a DateTimeFormatInfo, and fill in the properties according to
1374         // the CultureID.
1375         //
1376         ////////////////////////////////////////////////////////////////////////
1377
1378
1379         public virtual DateTimeFormatInfo DateTimeFormat {
1380             get {
1381                 Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
1382
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;
1390                 }
1391                 return (dateTimeInfo);
1392             }
1393
1394             set {
1395                 if (value == null) {
1396                     throw new ArgumentNullException("value",
1397                         Environment.GetResourceString("ArgumentNull_Obj"));
1398                 }
1399                 Contract.EndContractBlock();
1400                 VerifyWritable();
1401                 dateTimeInfo = value;
1402             }
1403         }
1404
1405
1406
1407         public void ClearCachedData() {
1408             s_userDefaultUICulture = null;
1409             s_userDefaultCulture = null;
1410
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;
1419
1420             CultureData.ClearCachedData();
1421         }
1422
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
1427         **Exceptions:
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());
1434             }
1435             return GetCalendarInstanceRare(calType);
1436         }
1437
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");
1442
1443             switch (calType) {
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());
1474             }
1475             return (new GregorianCalendar());
1476         }
1477
1478
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.
1482         **Returns:
1483         **Arguments:
1484         **Exceptions:
1485         **  ArgumentNull_Obj if the set value is null.
1486         ============================================================================*/
1487
1488
1489         public virtual Calendar Calendar {
1490             get {
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;
1497
1498                     System.Threading.Thread.MemoryBarrier();
1499                     newObj.SetReadOnlyState(m_isReadOnly);
1500                     calendar = newObj;
1501                 }
1502                 return (calendar);
1503             }
1504         }
1505
1506         /*=================================OptionCalendars==========================
1507         **Action: Return an array of the optional calendar for this culture.
1508         **Returns: an array of Calendar.
1509         **Arguments:
1510         **Exceptions:
1511         ============================================================================*/
1512
1513
1514         public virtual Calendar[] OptionalCalendars {
1515             get {
1516                 Contract.Ensures(Contract.Result<Calendar[]>() != null);
1517
1518                 //
1519                 // This property always returns a new copy of the calendar array.
1520                 //
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]);
1525                 }
1526                 return (cals);
1527             }
1528         }
1529
1530
1531         public bool UseUserOverride {
1532             get {
1533                 return (this.m_cultureData.UseUserOverride);
1534             }
1535         }
1536
1537 #if !FEATURE_CORECLR
1538         [System.Security.SecuritySafeCritical]  // auto-generated
1539         [System.Runtime.InteropServices.ComVisible(false)]
1540         public CultureInfo GetConsoleFallbackUICulture()
1541         {
1542             Contract.Ensures(Contract.Result<CultureInfo>() != null);
1543
1544             CultureInfo temp = m_consoleFallbackCulture;
1545             if (temp == null)
1546             {
1547                 temp = CreateSpecificCulture(this.m_cultureData.SCONSOLEFALLBACKNAME);
1548                 temp.m_isReadOnly = true;
1549                 m_consoleFallbackCulture = temp;
1550             }
1551             return (temp);
1552         }
1553 #endif
1554
1555         public virtual Object Clone()
1556         {
1557             Contract.Ensures(Contract.Result<Object>() != null);
1558
1559             CultureInfo ci = (CultureInfo)MemberwiseClone();
1560             ci.m_isReadOnly = false;
1561
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.
1564             if (!m_isInherited) 
1565             {
1566                 if (this.dateTimeInfo != null)
1567                 {
1568                     ci.dateTimeInfo = (DateTimeFormatInfo)this.dateTimeInfo.Clone();
1569                 }
1570                 if (this.numInfo != null)
1571                 {
1572                     ci.numInfo = (NumberFormatInfo)this.numInfo.Clone();
1573                 }
1574
1575             }
1576             else
1577             {
1578                 ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone();
1579                 ci.NumberFormat   = (NumberFormatInfo)this.NumberFormat.Clone();
1580             }
1581
1582             if (textInfo != null)
1583             {
1584                 ci.textInfo = (TextInfo) textInfo.Clone();
1585             }
1586
1587             if (calendar != null)
1588             {
1589                 ci.calendar = (Calendar) calendar.Clone();
1590             }
1591
1592             return (ci);
1593         }
1594
1595
1596         public static CultureInfo ReadOnly(CultureInfo ci) {
1597             if (ci == null) {
1598                 throw new ArgumentNullException("ci");
1599             }
1600             Contract.Ensures(Contract.Result<CultureInfo>() != null);
1601             Contract.EndContractBlock();
1602
1603             if (ci.IsReadOnly) {
1604                 return (ci);
1605             }
1606             CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone());
1607
1608             if (!ci.IsNeutralCulture)
1609             {
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);
1615                     }
1616                     if (ci.numInfo != null) {
1617                         newInfo.numInfo = NumberFormatInfo.ReadOnly(ci.numInfo);
1618                     }
1619
1620                 } else {
1621                     newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat);
1622                     newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat);
1623                 }
1624             }
1625             
1626             if (ci.textInfo != null)
1627             {
1628                 newInfo.textInfo = TextInfo.ReadOnly(ci.textInfo);
1629             }
1630
1631             if (ci.calendar != null)
1632             {
1633                 newInfo.calendar = Calendar.ReadOnly(ci.calendar);
1634             }
1635
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;
1639
1640             return (newInfo);
1641         }
1642
1643
1644         public bool IsReadOnly {
1645             get {
1646                 return (m_isReadOnly);
1647             }
1648         }
1649
1650         private void VerifyWritable() {
1651             if (m_isReadOnly) {
1652                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
1653             }
1654             Contract.EndContractBlock();
1655         }
1656
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
1661         {
1662             get { return Name == CultureInfo.InvariantCulture.Name; }
1663         }
1664
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)
1668         {
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
1672             // acceptable.
1673             // See code:Dictionary#DictionaryVersusHashtableThreadSafety for details on Dictionary versus 
1674             // Hashtable thread safety.
1675
1676             // retval is our return value.
1677             CultureInfo retval;
1678
1679             // Temporary hashtable for the names.
1680             Hashtable tempNameHT = s_NameCachedCultures;
1681
1682             if (name != null)
1683             {
1684                 name = CultureData.AnsiToLower(name);
1685             }
1686             
1687             if (altName != null)
1688             {
1689                 altName = CultureData.AnsiToLower(altName);
1690             }
1691
1692             // We expect the same result for both hashtables, but will test individually for added safety.
1693             if (tempNameHT == null)
1694             {
1695                 tempNameHT = Hashtable.Synchronized(new Hashtable());
1696             }
1697             else
1698             {
1699                 // If we are called by name, check if the object exists in the hashtable.  If so, return it.
1700                 if (lcid == -1)
1701                 {
1702                     retval = (CultureInfo)tempNameHT[name + '\xfffd' + altName];
1703                     if (retval != null)
1704                     {
1705                         return retval;
1706                     }
1707                 }
1708                 else if (lcid == 0)
1709                 {
1710                     retval = (CultureInfo)tempNameHT[name];
1711                     if (retval != null)
1712                     {
1713                         return retval;
1714                     }
1715                 }
1716             }
1717 #if FEATURE_USE_LCID
1718             // Next, the Lcid table.
1719             Hashtable tempLcidHT = s_LcidCachedCultures;
1720
1721             if (tempLcidHT == null)
1722             {
1723                 // Case insensitive is not an issue here, save the constructor call.
1724                 tempLcidHT = Hashtable.Synchronized(new Hashtable());
1725             }
1726             else
1727             {
1728                 // If we were called by Lcid, check if the object exists in the table.  If so, return it.
1729                 if (lcid > 0)
1730                 {
1731                     retval = (CultureInfo) tempLcidHT[lcid];
1732                     if (retval != null)
1733                     {
1734                         return retval;
1735                     }
1736                 }
1737             }
1738 #endif
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.
1741             try
1742             {
1743                 switch(lcid)
1744                 {
1745                     case -1:
1746                         // call the private constructor
1747                         retval = new CultureInfo(name, altName);
1748                         break;
1749
1750                     case 0:
1751                         retval = new CultureInfo(name, false);
1752                         break;
1753
1754                     default:
1755 #if FEATURE_USE_LCID
1756                         retval = new CultureInfo(lcid, false);
1757                         break;
1758 #else
1759                         return null;
1760 #endif
1761                 }
1762             }
1763             catch(ArgumentException)
1764             {
1765                 return null;
1766             }
1767
1768             // Set it to read-only
1769             retval.m_isReadOnly = true;
1770
1771             if (lcid == -1)
1772             {
1773                 // This new culture will be added only to the name hash table.
1774                 tempNameHT[name + '\xfffd' + altName] = retval;
1775
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);
1778             }
1779             else
1780             {
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);
1784                 
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;
1790
1791                 if ((retval.LCID == LCID_ZH_CHS_HANS && newName == "zh-hans")
1792                  || (retval.LCID == LCID_ZH_CHT_HANT && newName == "zh-hant"))
1793                 {
1794                     // do nothing because we only want zh-CHS and zh-CHT to cache
1795                     // by lcid
1796                 }
1797                 else
1798                 {
1799                     tempLcidHT[retval.LCID] = retval;
1800                 }
1801
1802 #endif
1803             }
1804
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.
1808             if(-1 != lcid)
1809             {
1810                 // Only when we modify the lcid hash table, is there a need to overwrite.
1811                 s_LcidCachedCultures = tempLcidHT;
1812             }
1813 #endif
1814
1815             s_NameCachedCultures = tempNameHT;
1816
1817             // Finally, return our new CultureInfo object.
1818             return retval;
1819         }
1820
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)
1825         {
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.
1829             if (culture <= 0) {
1830                 throw new ArgumentOutOfRangeException("culture",
1831                     Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
1832             }
1833             Contract.Ensures(Contract.Result<CultureInfo>() != null);
1834             Contract.EndContractBlock();
1835             CultureInfo retval = GetCultureInfoHelper(culture, null, null);
1836             if (null == retval)
1837             {
1838                 throw new CultureNotFoundException(
1839                     "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported"));
1840             }
1841             return retval;
1842         }
1843 #endif
1844
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)
1848         {
1849             // Make sure we have a valid, non-zero length string as name
1850             if (name == null)
1851             {
1852                 throw new ArgumentNullException("name");
1853             }
1854             Contract.Ensures(Contract.Result<CultureInfo>() != null);
1855             Contract.EndContractBlock();
1856
1857             CultureInfo retval = GetCultureInfoHelper(0, name, null);
1858             if (retval == null)
1859             {
1860                 throw new CultureNotFoundException(
1861                     "name", name, Environment.GetResourceString("Argument_CultureNotSupported"));
1862                 
1863             }
1864             return retval;
1865         }
1866
1867         // Gets a cached copy of the specified culture from an internal hashtable (or creates it
1868         // if not found).
1869         public static CultureInfo GetCultureInfo(string name, string altName)
1870         {
1871             // Make sure we have a valid, non-zero length string as name
1872             if (null == name)
1873             {
1874                 throw new ArgumentNullException("name");
1875             }
1876
1877             if (null == altName)
1878             {
1879                 throw new ArgumentNullException("altName");
1880             }
1881             Contract.Ensures(Contract.Result<CultureInfo>() != null);
1882             Contract.EndContractBlock();
1883
1884             CultureInfo retval = GetCultureInfoHelper(-1, name, altName);
1885             if (retval == null)
1886             {
1887                 throw new CultureNotFoundException("name or altName",
1888                                         String.Format(
1889                                             CultureInfo.CurrentCulture, 
1890                                             Environment.GetResourceString("Argument_OneOfCulturesNotSupported"), 
1891                                             name,
1892                                             altName));
1893             }
1894             return retval;
1895         }
1896
1897
1898         // This function is deprecated, we don't like it
1899         public static CultureInfo GetCultureInfoByIetfLanguageTag(string name)
1900         {
1901             Contract.Ensures(Contract.Result<CultureInfo>() != null);
1902
1903             // Disallow old zh-CHT/zh-CHS names
1904             if (name == "zh-CHT" || name == "zh-CHS")
1905             {
1906                 throw new CultureNotFoundException(
1907                             "name",
1908                             String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
1909                             );
1910             }
1911             
1912             CultureInfo ci = GetCultureInfo(name);
1913
1914             // Disallow alt sorts and es-es_TS
1915             if (ci.LCID > 0xffff || ci.LCID == 0x040a)
1916             {
1917                 throw new CultureNotFoundException(
1918                             "name",
1919                             String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
1920                             );
1921             }
1922             
1923             return ci;
1924         }
1925
1926         private static volatile bool s_isTaiwanSku;
1927         private static volatile bool s_haveIsTaiwanSku;
1928         internal static bool IsTaiwanSku
1929         {
1930             get
1931             {
1932                 if (!s_haveIsTaiwanSku)
1933                 {
1934                     s_isTaiwanSku = (GetSystemDefaultUILanguage() == "zh-TW");
1935                     s_haveIsTaiwanSku = true;
1936                 }
1937                 return (bool)s_isTaiwanSku;
1938             }
1939         }
1940
1941         //
1942         //  Helper Methods.
1943         //
1944         
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);
1949         
1950         [System.Security.SecuritySafeCritical]  // auto-generated
1951         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1952         internal static extern int nativeGetLocaleInfoExInt(String localeName, uint field);
1953
1954         [System.Security.SecurityCritical]  // auto-generated
1955         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1956         internal static extern bool nativeSetThreadLocale(String localeName);
1957
1958         [System.Security.SecurityCritical]
1959         private static String GetDefaultLocaleName(int localeType)
1960         {
1961             Contract.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
1962
1963             string localeName = null;
1964             if(InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName)))
1965             {
1966                 return localeName;
1967             }
1968             return string.Empty;
1969         }
1970
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);
1977
1978         [System.Security.SecuritySafeCritical] // auto-generated
1979         private static String GetUserDefaultUILanguage()
1980         {
1981             string userDefaultUiLanguage = null;
1982             if(InternalGetUserDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref userDefaultUiLanguage)))
1983             {
1984                 return userDefaultUiLanguage;
1985             }
1986             return String.Empty;
1987         }
1988         
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);
1995
1996         [System.Security.SecuritySafeCritical] // auto-generated
1997         private static String GetSystemDefaultUILanguage()
1998         {
1999             string systemDefaultUiLanguage = null;
2000             if(InternalGetSystemDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref systemDefaultUiLanguage)))
2001             {
2002                 return systemDefaultUiLanguage;
2003             }
2004             return String.Empty;
2005
2006         }
2007
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);
2014
2015 // Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
2016 #if FEATURE_CORECLR
2017         [System.Security.SecurityCritical]  // auto-generated
2018         [MethodImplAttribute(MethodImplOptions.InternalCall)]
2019         internal static extern String[] nativeGetResourceFallbackArray();
2020 #endif
2021     }
2022 }
2023