Sometimes it is useful to add properties to enum values. Translations or mapping are typical use cases. Here is how this could be accomplished.
Create an Attribute:
1 2 3 4 5 6 7 8 9 |
public class TranslationAttribute : Attribute { public int TranslationId { get; } public TranslationAttribute(int translationId) { TranslationId = translationId; } } |
Decorate some enum values:
1 2 3 4 5 6 7 8 9 10 11 |
public enum MyValues { [Translation(645)] First, [Translation(646)] Second, [Translation(730)] Third, [Translation(731)] Etc, } |
And finally apply some reflection magic:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static class MyExtensions { public static string Translate(this Enum self) { var enumType = self.GetType(); var enumValueMi = enumType.GetMember(self.ToString()); var appliedAttribute = enumValueMi.FirstOrDefault()?.GetCustomAttribute(typeof(TranslationAttribute), false) as TranslationAttribute; if (appliedAttribute != null) return TranslationProvider.GetTranslation(appliedAttribute.TranslationId); return self.ToString(); } } |
As you can see the magic is placed inside an extension method, this way you get a nice syntax:
1 |
var readableString = MyValues.First.Translate(); |
That’s it. Cheers!