Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum vs Constants/Class with Static Members?

Tags:

c#

enums

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 always 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?

like image 409
Caveatrob Avatar asked May 13 '11 22:05

Caveatrob


People also ask

Is it better to use enum or constant?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

Should I use enum for constants?

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Are enum members static?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


2 Answers

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.

like image 23
Jeff Mercado Avatar answered Oct 04 '22 02:10

Jeff Mercado


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(...);
}
like image 97
CodesInChaos Avatar answered Oct 04 '22 03:10

CodesInChaos