02 April 2004

Convert a string into an enum

The problem was raised in a project about use type code.

There are numerous type tables in Party etc DB schemas. Many of them used Meaningful VARCHAR2 or number as primary key, such like ECAR, BANK, FIXE or 01, 02 etc.

To use these type codes, the obvious non-brainer way is to hardcode them directly.

Or the political correct yet unpractical way: to access the type table whenever needed.

A better hardcode way is to define them in Enum type and combined with client side type tables. But in this scenario we have a problem: PKs are not natural sequential numbers and we rely on the assigned Enum value. Like this:

enum Colour
Red = 100,
Green =103,
Blue =140,

The problem arise when serialize the enum type across the wire. Client deserialisation (dominanted by MS WSDL tool) engine will construct a

enum Colour

Hence we loss the value.

We did come up with type class idea, but it was quite verbose and boring to implement.

Tim Sneath demonstrates a handy way
to convert string to Enum by using Enum.Prase(…)