Enums and Constants. Which to use when?

Draco picture Draco · Mar 5, 2009 · Viewed 70.6k times · Source

I was doing some reading on enums and find them very similar to declaring constants. How would I know when to use a constant rather than an enum or vice versa. What are some of the advantages of using enums?

Answer

Andrew Barrett picture Andrew Barrett · Mar 5, 2009

Use enums when you want to define a range of values that something can be. Colour is an obvious example like:

public enum Colour
{
    White,
    Red,
    Blue
}

Or maybe a set of possible things like: (Example I stole from here as I'm lazy)

[FlagsAttribute]
enum DistributedChannel
{
  None = 0,
  Transacted = 1,
  Queued = 2,
  Encrypted = 4,
  Persisted = 16,
  FaultTolerant = Transacted | Queued | Persisted
}

Constants should be for a single value, like PI. There isn't a range of PI values, there is just PI.

Other points to consider are:

  • a: Constants don't necessarily indicate a relationship between the constants, whereas an enumeration indicates that something can be one of the set defined by the enum.
  • b: A defined enumeration can help you with type checking when used as an argument. Constants are just values, so they don't provide any additional semantic information.