I frequently need a global hard-coded mapping between an enum and another object (a string in this example). I want to co-locate the enum and mapping definitions to clarify maintenance.
As you can see, in this example, an annoying class with one static field is created.
public enum EmailTemplates
{
// Remember to edit the corresponding mapping singleton!
WelcomeEmail,
ConfirmEmail
}
public class KnownTemplates
{
public static Dictionary<EmailTemplates, string> KnownTemplates;
static KnownTemplates() {
KnownTemplates.Add(EmailTemplates.WelcomeEmail, "File1.htm");
KnownTemplates.Add(EmailTemplates.ConfirmEmail, "File2.htm");
}
}
Sometimes the mapping class can have more function and a meaningful name, and the mapping activity can even be private. But that only pollutes the maintenance/correlation problem.
Anyone have a good pattern for this?
You can use attributes to annotate the enumeration and then use reflection to build the dictionary.
If you do this a lot you can create a more general generic function that combines enumeration values with an attribute associated with that enumeration value:
And use it like this:
For even more fun you can create an extension method:
Then calling
EmailTemplate.ConfirmEmail.FileName()
will returnFile2.htm
.Here is an approach which worked pretty well for me.
Now you can use reflection to map the Enum to the BaseErrWarn class:
Here is an example which uses this mapping to map an Enum to an object and then pull fields off of it:
Normally, when you want to add extra info or behaviors to your enum elements, that means you need a full blown class instead. You can borrow from (old-)Java the type-safe enum pattern and create something like this:
Now you can associate any properties or methods to your elements, like
Location
andRender
above.