A UI and Culture Friendly Replacement for Enumeration Types

Submitted on Jun 30, 2008, 12:27 p.m.

Using an enumeration to display a list of values in the user interface (UI) has obvious limitations. You'll be limited to the rules of enumeration values - no spaces, multi-words etc. You won't be able to offer localized versions of the strings used to describe each enumeration value. And you'll have to hard code and parse all possible values in order to present a list of values in a UI element.

Here's an article on five great patterns that can be used to create "look-up" or "reference" types (reference type in this case meaning a data structure that is used to represent a list of possible values that another type will depend on - like High, Medium, Low, or Fast and Slow).

Below is the code I used recently to create a type based on the descriptor pattern; a  reference type that will be used to assign a JobStatus to a Job class. What I like about this approach, is that with correct == and != operator overloads - it's a 1:1 swap with an existing enumeration type - so no code changes are required where an enumeration type may have been used initially.

The weakness of this pattern is that like enumerations - the class has to be coded - and so if the list of values changes the code will need to change too. That said, for small to medium size lists of "look-up" values (combined with a little code generation) this is a great way to offer type safe values as well as a UI and culture friendly list.

The ToString() override and the IList<JobStatius> GetValues() method make this type databinding friendly too.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104