开发者

Enum vs Constants/Class with Static Members?

开发者 https://www.devze.com 2023-03-06 01:10 出处:网络
I have a set of codes that are particular to the application (one to one mapping of the code to its name), and I\'ve been using enums in C# to represent them. I\'m not sure now if that is even necessa

I have a set of codes that are particular to the application (one to one mapping of the code to its name), and I've been using enums in C# to represent them. I'm not sure now if that is even necessary. The values never change, and they are 开发者_如何学Goalways going to be associated with those labels:

Workflow_Status_Complete = 1
Workflow_Status_Stalled = 2
Workflow_Status_Progress = 3
Workflow_Status_Complete = 4
Workflow_Status_Fail = 5

Should I use an enum or a class with static members?


Static members of type int seems to be inferior to an enum to me. You lose the typesafety of an enum. And when debugging you don't see the symbolic name but just a number.

On the other hand if an entry consists of more than just a name/integervalue pair a class can be a good idea. But then the fields should be of that class and not int. Something like:

class MyFakeEnum
{
   public static readonly MyFakeEnum Value1=new MyFakeEnum(...);
}


Use an enum. Even though your codes never change, it will be difficult to know what the value represents just by inspection. One of the many strengths of using enums.

enum RealEnum : uint
{
    SomeValue = 0xDEADBEEF,
}
static class FakeEnum
{
    public const uint SomeValue = 0xDEADBEEF;
}

var x = RealEnum.SomeValue;
var y = FakeEnum.SomeValue;
// what's the value?
var xstr = x.ToString(); // SomeValue
var ystr = y.ToString(); // 3735928559

Not even the debugger will help you much here, especially if there are many different values.


Check out the State Pattern as this is a better design. With the idea you are using you'll end up with a large switch/if-else statement which can be very difficult to keep up.


I would lean towards enums as they provide more information and they make your codes "easier to use correctly and difficult to use incorrectly". (I think the quote is from The Pragmatic Programmer.

0

精彩评论

暂无评论...
验证码 换一张
取 消