Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...