19

What is the point of having

enum SomeEnum : byte // <----
{
  SomeValue = 0x01,
  ...
}

when you have to make a cast just to assign it to the same type of variable as the enums underlying type?

byte b = (byte)SomeEnum.SomeValue;
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
Marlon
  • 19,924
  • 12
  • 70
  • 101

3 Answers3

15

Not much point, really, except that if the default underlying type (int) is not enough for you, ie. you want to use higher integer values than that then you can make it long. This can be useful when you have a [Flags] enum with more than 32 values.

You can make it byte or short just to restrict the range of values, but it will actually still take 4 bytes when used as a local variable (ie. same as int). It may however occupy less memory if used as an array.

Pharap
  • 3,826
  • 5
  • 37
  • 51
EMP
  • 59,148
  • 53
  • 164
  • 220
  • 5
    Do you have a citation for that last part? – porges Apr 16 '10 at 04:39
  • 14
    For a single variable the last part may be correct due to padding. However, I believe if you have a large array of an enum with an underlying type of byte, that will be like having a `byte[]` instead of an `int[]`. – Jon Skeet Apr 16 '10 at 05:20
  • Yes, what Jon Skeet said. But who the hell uses an array of enums? :) – EMP Apr 16 '10 at 05:54
  • 12
    @EMP: I do...a big one too, which is why I'm here ! – mpen Feb 04 '12 at 19:28
4

From enum (C# Reference)

The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is needed to convert from enum type to an integral type.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
3

Apart from the technical reasons why... There is a design principle here.

specifying the enum as having byte storage is an implementation detail. Using the enum is a different issue, you should not have to know or care about the implementation details of it.

In client code, the fact that you are using an enum should mean that you are in fact meaning to use an enum, not a byte, or long etc. Otherwise why not just use the datatype you mean.

Strongly type languaged such as C# strive to make it just a little harder to step outside your coding "contracts" this usually helps make app design just that little bit better.

Now of course I am not saying that there are not times that you have to get involved in implementation details, a good example is in say an object relational mapper (ORM) where you are mapping a C# datatype to a database datatype, enums are a good example where you have to then know its storage type to map it. But in these cases, its IMO good to have to explicity cast or reflect, its a good flag in reviews that here you are specifically stepping outside the usual usage.

Tim Jarvis
  • 18,465
  • 9
  • 55
  • 92