Fallback Values for Backwards Compatible Enums

Came up with a nice idea while driving today about versioning enums.

Say you have an application that saves files. Every file has a font specific to it and it is saved as the following enum (v1.0):

public enum Font
{
Tahoma,
Arial,
}

When v1.1 comes out, you want to be able to add a new value to the enum, for the font “Courier New”. However, once you do that, you won’t be able to open files that use it at all in v1.0.
This is where the idea of a fallback value comes in. What we want is that whenever a file with “Courier New” as the selected font is displayed by version 1.0, it will be displayed using “Tahoma”.

This can not be done with the above enum. However, there is a solution, in the following form:

[Flags]
public enum Font
{
Tahoma = 0x01,
Arial  = 0x02,
CourierNew = 0x05,
}

The idea is that since CourierNew also contains the bit for the Tahoma value, the first two statements will be true but the third won’t:

Font courier = Font.CourierNew;
bool isCourierNew = ((courier & Font.CourierNew) == Font.CourierNew),
isTahoma     = ((courier & Font.Tahoma)     == Font.Tahoma),
isArial = ((courier & Font.Arial) == Font.Arial);

If we wanted to add a new value in v1.2 for “Veredana” with a fallback to “Courier New”, we will simply add a field with the value 0x0D (8 is the next unused bit or’d by 5, the value of “Courier New”).

The only limitation to this is that you can only use as many bits as there are in the types enum can inherit.

Advertisements

One thought on “Fallback Values for Backwards Compatible Enums

  1. I like the idea, it alleviates the one big problem I have with Enums.
    But it doesn’t completely solve it. An alternative is to use the Singleton pattern. It’s not pretty but at least arbitrary extensible.

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