Enumerated Types versus classes and globalization/localization

Enumerated types are all represented as integers (unless you inherit from another base type, but, for the sake of argument, let’s say an integer. You can learn more about enumerated data types in the article, Extolling the Virtues of Enumerated Types). I have frequently seen them used to represent things such as colors, days of the week, status of an object, or even type of an object (e.g. enum Person { Teacher, Student, Principal, Parent }).
 
The problem with enumerated types is that there is no ability to easily manage globalization/localization of the information they are intended to store without having if- or case-statements all over the place to handle it. The alternative is to convert your enumerated types to classes.
 
e.g.
 

abstract class Color {

    abstract string Name { get; }

}

class Red : Color {

    public string Name { get { return "Red"; } }

}

 
This representation does not get us significantly closer to a globalized type until we make use of resource files (in the sample below I am using a strongly typed resource to retrieve the string value. Learn more about localization practices and strongly-typed resources in TheServerSide.Net article, Localization Practices for .NET 2.0: It’s Still About The Architecture).
 
 e.g.

class Red : Color {

    public string Name { get { return Resources.ResourceFile.ColorRed; } }

}

With this small change we have effectively made our type localizable and can now use the values in the user interface.

So, when would you recommend the use of enumerated types? Some say you use them whenever you have a fixed set of constants. I would add to that to say that you should use them when you are representing numerically coded data that is not being presented in the user interface.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s