Why must I cast on the way out of an emumeration?

Hello,

It's hardly a major issue, but I do occasionally get irritated when the compiler tells me that something like

Logger.Log("portfolio selected", Developers.carlos);

doesn't work, because I haven't casted Developers.carlos as an int (which I never think to do, as I have explicitly defined the Developers enumeration as being of type int (public enum Developers : int)).

Just wondered if there was a good reason behind this. Obviously it's not very important, but brevity in code is always nice if it doesn't compromise functionality or readability...

Thanks,
Carlos



Answer this question

Why must I cast on the way out of an emumeration?

  • NeeTrihT

    Excellent answers, thanks a lot.

  • leumas111

    You are more then welcome!

    Happy coding!


  • A.Hadi

    This is only when you want to put an enum flag in a int. When your Log method accepts an Developers enum it isn't needed.

    Enums are user-defined value types. If you take a look at the inheritance you see:

    System.Enum
    System.ValueType
    System.Object

    C# is strict about this, because in runtime the int is an representation, but only at runtime. There is no reason that your enum internally value prepresentation is something elkse, we as developers attch the additinal meaning to an enums underlying value. We can only specify numeric values, so we can use bit manipulation. You can use the Flags attribute to indicates that your enum must be treated as a bit field.


  • dwj

    C# supports implicit casting only if corresponding implicit casting operator is defined to the type. And Enum-class does not define implicit casting operator to int.

    As a former C++ programmer, I was also irritated at first, but i have realized that such strict typing prevents many errors, since you got to know exactly what you are doing when you cast a type to another.

    It's true that sometimes casting makes code harder to read, but thats the price we have to pay for the strong typing. One (int)Developers.Carlos does though make no harm...

  • Why must I cast on the way out of an emumeration?