Enums and Constants. Which to use when?

前端 未结 6 1891
遇见更好的自我
遇见更好的自我 2020-12-04 18:51

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

6条回答
  •  抹茶落季
    2020-12-04 19:29

    What's missing from the other answers is that enums have an integer base type. You can change the default from int to any other integral type except char like:

    enum LongEnum : long {
        foo,
        bar,
    }
    

    You can cast explicitly from and implicitly to the the base type, which is useful in switch-statements. Beware that one can cast any value of the base type to an enum, even if the enum has no member with the appropriate value. So using always the default section in a switch is a good idea. BTW, .NET itself allows even floating point valued enums, but you can't define them in C#, although I think you can still use them (except in switch).

    Furthermore, using enums gives you more type safety. If you intend to use e.g. int constants as method parameters, then I could call the method with any int value. Granted, via casting it can happen with enums, too, but it won't happen accidentally. Worse is the possibility to confuse the order of parameters.

    void method(int a, int b) {...}
    

    If constant A only may go into a and constant B only may go into b, then using two different enum types will uncover any misuse during the compilation.

提交回复
热议问题