1

I have the following enum:

enum Crank { X = 0, Y = 1 }

However when I try

if (x == Crank.X)

I get an error indicating

cannot convert from Crank to int

Where do i go wrong?

  • 3
    Assuming `x` is an int, you can cast the enum value to an int to compare them, i.e. `if (x == (int)Crank.X)` – stuartd Jul 22 '16 at 22:55
  • thanks. however why do I need to cast it?? I gave it value 0... – Natalia Userbon Jul 22 '16 at 22:56
  • 2
    From docs: The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is necessary to convert from enum type to an integral type. – guipivoto Jul 22 '16 at 22:57
  • thanks both for the help!! – Natalia Userbon Jul 22 '16 at 22:58
  • 2
    See [Why enums require an explicit cast to int type?](http://stackoverflow.com/questions/4728295/why-enums-require-an-explicit-cast-to-int-type) for a great explanation of why this is required. – stuartd Jul 22 '16 at 23:02
  • I am mistaken here:) @stuartd – George Chen Jul 22 '16 at 23:06
  • @stuartd even though sure, it makes sense, but you can do `enum Crank : int { //values }` and it still won't let you. That is poor implementation, you should be able to compare ints if you define it to only take ints. – Dispersia Jul 22 '16 at 23:12

1 Answers1

2

If x is of type integer, you need to cast the enum value to an int to compare if(x==(int)Crank.X)

Jaya
  • 3,721
  • 4
  • 32
  • 48