enum with underlying type


C

coltrane

I am just learning c# and I have a question regarding enums.

I have an enum with a underlying type of int

enum numbers : int {
one = 1,
two = 2,
three = 3
}
I then try to assign an enum item to an integer:

int x = numbers.one;

I get the following error:

Cannot implicitly convert type 'FunWithEnums.Program.numbers' to
'int'. An explicit conversion exists (are you missing a cast?)

I thought that if I set the underlying class to int I would not have
to cast.

If I still have to cast the enum then what is the point of setting the
underlying type

thanks for the help

john
 
Ad

Advertisements

G

Göran Andersson

coltrane said:
I am just learning c# and I have a question regarding enums.

I have an enum with a underlying type of int

enum numbers : int {
one = 1,
two = 2,
three = 3
}
I then try to assign an enum item to an integer:

int x = numbers.one;

I get the following error:

Cannot implicitly convert type 'FunWithEnums.Program.numbers' to
'int'. An explicit conversion exists (are you missing a cast?)

I thought that if I set the underlying class to int I would not have
to cast.

If I still have to cast the enum then what is the point of setting the
underlying type

thanks for the help

john

You specify the underlying type if you want to change how the enum is
stored. If you for example have a large array of enum values, you might
want to preserve space by using a byte as underlying type instead of the
default type int.

You still have to cast the value when you convert values between enum
and int. This is for type safety so that you can't mix enum values with
int values by mistake.

If you cast a value that has the same type as the underlying type of the
enum, it's only to show that you really want the conversion. The actual
code that will be generated in the end is just an assignment, as there
is no need to do an actual casting.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top