The best way to represent a word in a class library used in multilingual applications
I am creating a class library with some commonly used classes like persons, addresses, etc. This library will be used in a multilingual application and I am looking for the most convenient way to represent the gender of people.
Ideally, I would like to be able to code like this:
Person person = new Person { Gender = Genders.Male,
FirstName = "Nice",
LastName = "Dude" }
if (person.Gender == Genders.Male)
Console.WriteLine("person is Male");
Console.WriteLine(person.Gender); //Should output: Male
Console.WriteLine(person.Gender.ToString("da-DK"));
//Should output the name of the gender in the language provided
List<Gender> genders = Genders.GetAll();
foreach(Gender gender in genders)
{
Console.WriteLine(gender.ToString());
Console.WriteLine(gender.ToString("da-DK"));
}
What would you do? Enumeration and specialized gender class? But what about localization?
Edit: I would like to point out that this question is at least about how to code some classes that allow you to write code like above, I don't have a Gender class or gender enumeration, I am trying to figure out how to write code that would include the above code. What would be the Genders class? Would you use an enumeration for Genders?
Regards
Jesper Hauge
a source to share
I would not use an enum and would probably decide to create a class Gender
with an internal constructor as well as a static class Genders
to contain the available parameters as properties. This would be basically the same approach that is used in .NET, for example, for System.Drawing.Color
and its associated class Colors
.
It's easier to deal with globalization if I have a class instead of an enum.
a source to share
In your business and data classes, you don't have to worry about doing localization, as localization (should be) is a fully mapped operation. Use exactly what you have, as it is readable and maintainable.
To localize values, .NET already has a built-in resource manager that automatically selects the appropriate resource value based on the value CurrentUICulture
. For this particular scenario, you can use a value ToString()
from your enum as a key in the resource file. This will allow you to create different files for different cultures (as is convention and what the resource manager expects), each with a different meaning for "Male"
and "Female"
.
http://msdn.microsoft.com/en-us/magazine/cc163609.aspx
http://msdn.microsoft.com/en-us/library/aa309421%28VS.71%29.aspx
a source to share
Another option is to create an extension method for your enumerated type. For instance:
public static class GenderExtensions
{
public static string ToLocalizedText(this Gender gender)
{
// Lookup Localized content based on state of 'gender'
return "This person is male";
}
}
And then you can just write
gender.ToLocalizedText()
instead
gender.ToString()
a source to share