Recently, I ran into a problem , where I need to iterate through an enum, and get a localized description of its member. As an example, I’ll use enum Faculties.
public enum Faculties
{
Engineeering=1,
Economy=2,
Physchology=3,
Law=4,
Pharmacy=5
}
How do we connect enum member with resource file (.resx)?
We can use a DescriptionAttribute and add it to all enum members.
The trick here is we set the description to strongly type property name .
So here is our final enum:
public enum Faculties
{
[Description("Faculties_Engineering")]
Engineering = 1,
[Description("Faculties_Economy")]
Economy = 2,
[Description("Faculties_Physchology")]
Physchology = 3,
[Description("Faculties_Law")]
Law = 4,
[Description("Faculties_Pharmacy")]
Pharmacy = 5
}
And finally we add extension method for Faculties enum
public static class Extensions
{
public static string ToLocalizedString(this Faculties val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
string description = attributes.Length > 0 ? attributes[0].Description : string.Empty;
string result = string.Empty;
if (!string.IsNullOrEmpty(description))
{
result = typeof(LanguageResource).GetProperty(description).GetValue(null, null) as string;
}
return result;
}
}