Refactor enum->class
Every so often, I see a C# user say they’d like to add a method to an enum. Maybe it’s [Flags] and they want to verify that the combination of flags is legal according to their business rules. Or maybe they’re in the process of moving to something more OO, involving inheritance instead of constants.
Anyway, I’ve been trying to think about how to do it. I don’t know yet if there’s anything really compelling here, I’m still exploring.
The idea is a simple code transformation that gets you out of an enum and into a class, as simply as possible.
In my experiments, I’m starting with this blob of code. The challenge is to refactor it so that ‘E’ is not an enum, while maintaining basically the same semantics as when you started.
enum E
{
a, b, c
}
class Program
{
void F(E e)
{
E e2 = E.a;
switch (e)
{
case E.a:
break;
case E.b:
break;
case E.c:
break;
}
if (e == E.a)
{
return;
}
}
}
BTW, TheoY and I chatted about this today while I made tea, which is part of inspiration behind writing this entry.
Edit: I want you to post your ideas about how you might refactor this. Duh me for not saying so earlier!
Comments
Anonymous
May 28, 2004
The comment has been removedAnonymous
May 29, 2004
public class C
{
public const int a = 0;
public const int b = 1;
public const int c = 2;
private int id = -1;
public static implicit operator int (C c)
{
return c.id;
}
public static implicit operator C (int i)
{
return new C(i);
}
public static bool operator == (C c, int i)
{
return (int)c == i;
}
public static bool operator != (C c, int i)
{
return (int)c != i;
}
private C(int id)
{
this.id = id;
}
}Anonymous
May 30, 2004
You did of course understand that the class C should be renamed to E.
More details at http://home.online.no/~teyde/blog/Refactorenum-class.htmlAnonymous
May 30, 2004
The answers you two provided match the two that we came up with. I wonder if there are any other interesting solutions out there?Anonymous
June 13, 2009
PingBack from http://barstoolsite.info/story.php?id=396Anonymous
June 19, 2009
PingBack from http://debtsolutionsnow.info/story.php?id=2250