Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I prefer an enum to a struct with constant values

Tags:

c#

enums

struct

A struct with constants:

public struct UserType {   public const int Admin=1;   public const int Browser=2;   public const int Operator=3; } 

And now let's use an enum for the same purpose:

public enum UserType {   Admin=1,   Browser,   Operator }   

Both are allocated on the stack. In both cases I will say UserType.Admin. And with the struct way I will not have to cast to int to get the underlying value.I know that with the enum version it's guaranteed that one and only one of the three values will be used, whereas with the struct version any integer can be used, which means any value between Int32.MinValue and Int32.MaxValue. Is there any other benefit of preferring enums besides this one?

like image 686
Mikayil Abdullayev Avatar asked Nov 17 '12 09:11

Mikayil Abdullayev


People also ask

Why is enum better than constant?

Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.

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.

When should we use an enum over a regular constant variable?

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.

What is a key advantage of using an enum?

The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future. Makes code easier to read, which means it is less likely that errors will creep into it.


1 Answers

Is there any other benefit of preferring enums besides this one?

Clarity.

Suppose you have a field or a method parameter which will always have one of those three values. If you make it the enum type, then:

  • You can't accidentally assign it some arbitrary integer value. (You can deliberately cast any int value to the enum type, but you'd have to do so explicitly.)
  • It's clear what kind of information that value is meant to represent

These are incredibly important benefits in writing code which is easy to maintain in the future. The more you can make your code naturally describe what you're trying to achieve, the better.

like image 55
Jon Skeet Avatar answered Oct 06 '22 09:10

Jon Skeet