Tips related to Create a multilingual a to z list in C#
When ever I'm doing something with localization, I create a service class to wrap the different logic. This could be getting labels from Umbraco's dictionary according to a given culture, or as here, getting the localized alphabet. I can then register it with my dependency injection container - eg. as a singleton.
A benefit from this approach opposed to a static class is that I can extend the class, and override some of it's methods. If the class grows in complexity, I could also consider having it backed by an interface. This could make testing and mocking it easier.
When needing the logic in a Razor view, the service can be injected like @inject MyLocalizationService LocalizationService
- or in a similar way in C# classes.
When working with the service in a Razor view, it's probably unlikely that we'd need to specify another culture than the culture of the current thread, so I've added a method overload for both the GetAlphabet()
and the GetFirstLetter()
methods respectively. This way we can call the parameterless method without specifying a culture - but we still have the option to specify one via the method overload if we need to.
Compared to my example on Our, I've also changed the output type from string[]
to IReadOnlyList<string>
(string[]
implements IReadOnlyList<string>
). Arrays are mutable as you can change each item of the array, whereas IReadOnlyList<string>
is immutable - unless you cast it back to string[]
.
I also relalized that I missed W in the English alphabet, so I've fixed that as well