Search code examples
.netlocalizationresx

How does the ResourceManager handle culture Fallback for custom cultures?


I created a custom culture called es-CO-ZF. This culture is based of es-CO:

var cultureInfo = new CultureInfo("es");
var regionInfo = new RegionInfo("CO");

var infoBuilder = new CultureAndRegionInfoBuilder(
    "es-CO-ZF", CultureAndRegionModifiers.None);

infoBuilder.LoadDataFromCultureInfo(cultureInfo);
infoBuilder.LoadDataFromRegionInfo(regionInfo);
infoBuilder.Register();

The following is a console printout of the CultureInfo object:

Name: . . . . . . . . . . . . . es-CO-zf
EnglishName:. . . . . . . . . . Spanish
NativeName: . . . . . . . . . . español
TwoLetterISOLanguageName: . . . es
ThreeLetterISOLanguageName: . . spa
ThreeLetterWindowsLanguageName: ESP

In order to test culture fallback I created the following RESX files:

App.resx (en-US, default culture)
  String1 > English
App.es.resx
  String1 > español
App.es-CO.resx
  String2 > Colombia
App.es-CO-ZF.resx
  String2 > Colombia Custom

And obtained the localized strings as follows:

CultureInfo culture = CultureInfo.CreateSpecificCulture("en-CO-ZF");
var string1 = App.ResourceManager.GetString("String1", culture);
var string2 = App.ResourceManager.GetString("String2", culture);

When using the built-in culture es-CO I got the following results:

String1: español
String2: Colombia

So when using the custom culture I expected the following result:

String1: español
String2: Colombia Custom

But I got:

String1: English
String2: Colombia Custom

So what I'm seeing is that the resource manager does not appear to know, or figure out, that the base language for the custom culture is Spanish, even though according to the CultureInfo object and it's languages properties the base language is Spanish.

Am I doing something wrong?

What should I do so that the ResourceManager falls back to es for my custom culture?


Solution

  • When creating a custom culture set the Parent property of the CultureAndRegionInfoBuilder object to whichever culture you wish it to fall back to when localization for the custom culture is not available.

    var cultureInfo = new CultureInfo("es");
    var regionInfo = new RegionInfo("CO");
    
    var infoBuilder = new CultureAndRegionInfoBuilder(
        "es-CO-ZF", CultureAndRegionModifiers.None);
    
    infoBuilder.LoadDataFromCultureInfo(cultureInfo);
    infoBuilder.LoadDataFromRegionInfo(regionInfo);
    
    //set the parent for culture fallback
    infoBuilder.Parent = new CultureInfo("es-CO");
    
    infoBuilder.Register();