Page 198 - CSharp/C#
P. 198

which occurs at runtime. Expressions in an interpolated string must reference names in the current
        context and need to be stored in resource files. That means that if you want to use localization you
        have to do it like:


         var FirstName = "John";

         // method using different resource file "strings"
         // for French ("strings.fr.resx"), German ("strings.de.resx"),
         // and English ("strings.en.resx")
         void ShowMyNameLocalized(string name, string middlename = "", string surname = "")
         {
             // get localized string
             var localizedMyNameIs = Properties.strings.Hello;
             // insert spaces where necessary
             name = (string.IsNullOrWhiteSpace(name) ? "" : name + " ");
             middlename = (string.IsNullOrWhiteSpace(middlename) ? "" : middlename + " ");
             surname = (string.IsNullOrWhiteSpace(surname) ? "" : surname + " ");
             // display it
             Console.WriteLine($"{localizedMyNameIs} {name}{middlename}{surname}".Trim());
         }

         // switch to French and greet John
         Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
         ShowMyNameLocalized(FirstName);

         // switch to German and greet John
         Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
         ShowMyNameLocalized(FirstName);

         // switch to US English and greet John
         Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
         ShowMyNameLocalized(FirstName);


        If the resource strings for the languages used above are correctly stored in the individual resource
        files, you should get the following output:

              Bonjour, mon nom est John
              Hallo, mein Name ist John
              Hello, my name is John


        Note that this implies that the name follows the localized string in every language. If that is not the
        case, you need to add placeholders to the resource strings and modify the function above or you
        need to query the culture info in the function and provide a switch case statement containing the
        different cases. For more details about resource files, see How to use localization in C#.

        It is a good practice to use a default fallback language most people will understand, in case a
        translation is not available. I suggest to use English as default fallback language.



        Recursive interpolation




        Although not very useful, it is allowed to use an interpolated string recursively inside another's
        curly brackets:




        https://riptutorial.com/                                                                             144
   193   194   195   196   197   198   199   200