tags:

views:

77

answers:

4

if I have a very simple enum of ints like this.

  enum alignment { left, center, right}

Where I want the datatype to be an int, which I understand is the default, and the values to be left = 0, center = 1, right = 2.

But if I try and use a value from the enum like

header.Alignment = alignment.center;

I am told that I need to cast alignment.center to an int. which is no big deal but I am wondering if I am doing something wrong or is that just the way enums work.

+5  A: 

If the header.Alignment property is an integer you will need to cast it.

That said it would probably make more sense to change the Alignment property to actually be of type Alignment. Then you would not need to cast when you are setting it and you would still have access to the integer value if you ever needed it.

Shaun Bowe
+8  A: 

if header.Alignment is of type int, then yes, you always have to cast to an int.

You could make header.Alignment of type alignment, and then you'd never have to cast. If you're dealing with legacy or third-party code that only accepts an int, however, you're out of luck.

Randolpho
+3  A: 

The enum backing store is an int, but you can't use it as an int easily. the idea of an enumeration is to have a strongly typed collection of constants so you can use them as, say, an alignment value. when you us it as an int, you throw that strong typing out the window. You should change the Alignment property of your header to be of type Alignment rather than an int.

Scott M.
+1 for mentioning strong typing.
Randolpho
A: 

Yes. An explicit cast is needed to convert from enum type (alignment) to an integral type.

Shaji