9 thoughts on “Enum conversion. Why Oh Why?

  1. What’s the problem with:
    byte b = (byte)FooEnum.Will;
    ?

    It’s only six characters longer, and it clearly states what it does.

  2. It *does* just work. It clearly forces you to separate enums from raw types both in your thinking and in your code, and makes the practice of conflating the two much more challenging to pull off accidentally.

  3. You could use a struct instead:

    public struct FooNum
    {
    public const byte Will = 1;
    ….
    }

    Since it’s a const, you can still switch on it (although you don’t get the nice VS switch snippet support). Just an option. I do this in a couple places and it works well for those situations.

  4. Because a byte is a byte, and an enum is an enum, regardless of how it is stored.

    They drew a line in the sand regarding implicit casting. If it’s too annoying, well, there’s always VB.

  5. @Pawel Piotrowicz
    @Justice
    @Steve Py

    Although it doesn’t appear this way (through the post). I mostly agree with everyone 🙂 – This is the exact feedback I was hoping to receive.

    I spent some time working with some legacy code where just about every “Entity” had a byte property type (that ‘mapped’ to a related Enum type). The conversion of the two back and forth has become extremely annoying, (it’s only 6 characters isn’t just 6 characters in my case – it’s more like wasted time…). Unfortunately I lost sight of some of the ideas given by the good comments made above.

    Thanks everyone for clarifying.

  6. Well I don’t get it why you should not implicitly cast from enum to byte. However, I find it very logical that you need to cast from byte to enum explicitly.

  7. Why _should_ this be possible?
    These are two different datatypes, and you have to be explicit about converting them. This concept is called ‘type safety’…

Comments are closed.

Proudly powered by WordPress | Theme: Code Blog by Crimson Themes.