Enum conversion. Why Oh Why?

November 15th, 2009

image

 

What MSDN says: enum (C# Reference)

image

 

Why can’t this just work?

Jason Jarrett Esoterica

  1. Pawel Piotrowicz
    November 15th, 2009 at 02:17 | #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. Justice
    November 15th, 2009 at 02:20 | #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. November 15th, 2009 at 13:25 | #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. Steve Py
    November 15th, 2009 at 15:52 | #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. Hakan Forss
    November 15th, 2009 at 16:53 | #5

    In VB.NET i does. This has bitten me once or twice!

  6. November 15th, 2009 at 17:18 | #6

    @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.

  7. November 16th, 2009 at 13:43 | #7

    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.

  8. November 20th, 2009 at 21:11 | #8

    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.