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?
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:
intvalue to the enum type, but you’d have to do so explicitly.)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.