Related: Get enum from enum attribute
I want the most maintainable way of binding an enumeration and it's associated localized string values to something.
If I stick the enum and the class in the same file I feel somewhat safe but I have to assume there is a better way. I've also considered having the enum name be the same as the resource string name, but I'm afraid I can't always be here to enforce that.
using CR = AcmeCorp.Properties.Resources;
public enum SourceFilterOption
{
LastNumberOccurences,
LastNumberWeeks,
DateRange
// if you add to this you must update FilterOptions.GetString
}
public class FilterOptions
{
public Dictionary<SourceFilterOption, String> GetEnumWithResourceString()
{
var dict = new Dictionary<SourceFilterOption, String>();
foreach (SourceFilterOption filter in Enum.GetValues(typeof(SourceFilterOption)))
{
dict.Add(filter, GetString(filter));
}
return dict;
}
public String GetString(SourceFilterOption option)
{
switch (option)
{
case SourceFilterOption.LastNumberOccurences:
return CR.LAST_NUMBER_OF_OCCURANCES;
case SourceFilterOption.LastNumberWeeks:
return CR.LAST_NUMBER_OF_WEEKS;
case SourceFilterOption.DateRange:
default:
return CR.DATE_RANGE;
}
}
}
You can add DescriptionAttribute to each enum value.
public enum SourceFilterOption
{
[Description("LAST_NUMBER_OF_OCCURANCES")]
LastNumberOccurences,
...
}
Pull out the description (resource key) when you need it.
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
Edit: Response to comments (@Tergiver). Using the (existing) DescriptionAttribute in my example is to get the job done quickly. You would be better implementing your own custom attribute instead of using one outside of its purpose. Something like this:
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inheritable = false)]
public class EnumResourceKeyAttribute : Attribute
{
public string ResourceKey { get; set; }
}