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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)