1

I have the following code:

public enum rkError : int {EC_SUCCESS,
    EC_INVALID_FILE, 
    EC_UNDEFINED_HEADER, 
    EC_FILE_NOT_FOUND, 
    EC_CANNOT_CREATE};

...then, latter on:

int ok;
.
.
.
ok = hdr.Load();
if(ok!=rkError.EC_SUCCESS) return ok;
.
.
.

...as far as I understand, both ok and rkError.EC_SUCCESS are int, however the compiler complaints:

Error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'test.rkError'

so in order to run my program I must change the if line like this:

if(ok!=(int) rkError.EC_SUCCESS) return ok;

I don't understand why this is happening, since I took care of explicitly define rkError as int.

I'm using MonoDevelop instead of Visual Studio. Is this normal? am I doing something wrong?

george b
  • 199
  • 1
  • 1
  • 8

1 Answers1

4

rkError is not int. It's an enum backed by int. That's not the same.

And yes, you have to cast enum value to underlying primitive type to compare it with another primitive value.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Is there any way I can avoid casting? I'm really using enum here because I can't find something equivalent to #define in C/C++. – george b Feb 13 '14 at 02:29
  • 1
    Make your `Load` method return `rkError` instead of `int`. – MarcinJuraszek Feb 13 '14 at 02:33
  • 1
    `const static int EC_SUCCESS = 0;` is a closer analog to `#define` than `enum`. – Peter Gluck Feb 13 '14 at 02:36
  • @PeterGluck it works only inside the class in which EC_SUCCESS is declared, outside it (in another project), the compiler still requires me to cast. I could quite easily solve this in C/C++, but in C# I am lost. – george b Feb 13 '14 at 03:02
  • C# is a different language to C++, with different rules and syntax. Not *everything* in C++ has a syntactically equivalent analog in C#. – Baldrick Feb 13 '14 at 03:10
  • @georgeb Add the `public` modifier and you can access the constant from anywhere by prepending the class name, e.g., `rkError.EC_SUCCESS`. – Peter Gluck Feb 13 '14 at 17:55