I hear you.
I spent quite some time on exactly the same issue myself. First, I tried to
implement something similar to Color/KnowColor pair in System.Drawing. i.e.:
enum KnownSex{Male, Female};
class Sex
{
public static readonly Male = new Sex(KnownSex.Male);
public static readonly Female = new Sex(KnownSex.Female);
...
public static Sex FromKnownSex(KnownSex sex)
{
switch (sex)
{
case KnownSex.Male:
return Sex.Male;
.....
}
}
[ And please, don't laugh at the notion of "unknown sex"! I live in
Thailand, I've seen strange things ;-) ]
The idea was to have object properties (like Person.Sex) to be set to enum
values, but use objects of Sex class in comboboxes etc. But... too much work
for too little. I settled down on using singletons. It just feel "more
right" than enums. And if/else if doesn't bother me at all. All my "enum
classes" have static field called List which returns all singleton objects
of this class, not just those defined in static fields like Male and Female
instances above. I've seen from your other posting that you're doing the
same with GetValues method; good, I might not be completely crazy.
Why can't we use switches with singleton objects? I know that the compiler
cannot optimize them like constant values but the same is true for strings
and they are allowed in switches.
I guess that you can use strings in switches because they are immutable.
As for localizing the enums, earlier today I posted some code which might
give you some food for thought. I'm repeating it below.
Alexander
---------------------------------------------------------
class FriendlyNameAttribute : Attribute
{
public readonly string Value;
public FriendlyNameAttribute(string value)
{
Value = value;
}
}
enum MyEnum {
[FriendlyName("Value of One")]
One,
[FriendlyName("Value of Two")]
Two,
Three
};
class MainClass
{
public static void Main(String[] args)
{
foreach (FieldInfo fi in typeof(MyEnum).GetFields())
{
FriendlyNameAttribute[] names =
(FriendlyNameAttribute[])fi.GetCustomAttributes(typeof(FriendlyNameAttribu te),
true);
if (names.Length > 0)
{
Console.WriteLine(names[0].Value);
}
else
{
Console.WriteLine(fi.Name);
}
}
}
}