Casting enums into ints

There is something that I cannot understand in C#. You can cast an out-of-range int into an enum and the compiler does not flinch. Imagine this enum:

enum Colour
    Red = 1,
    Green = 2,
    Blue = 3

Now, if you write:

Colour eco;
eco = (Colour)17;

The compiler thinks that’s fine. And the runtime, too.


Why did the C# team decide to make this possible? This decision misses the point of using enums, I think, in scenarios like this:

void DoSomethingWithColour(Colour eco)
    //do something to eco.

In a strong-typed language like C#, I would like to assume that eco will always hold a legal Colour value. But this is not the case. A programmer could call my method with a value of 17 assigned to eco (as in previous code snippet), so the code in my method must not assume that eco holds a legal Colour value. I need to test for it explicitly and handle the exceptional values as I please. Why is this?

In my humble opinion, it would be much nicer if the compiler issued an error (or even a warning) message when casting an out-of range int into an enum, if the int value is known at compile time. If not, the runtime should throw an exception at the assignment statement.

What do you think?


3 Responses to “Casting enums into ints”

  1. 1 rp 11 January 2005 at 12:27

    100% agreed. I think it’s one of those cases of “C mentality”: someone raised on C regards an enum as a bunch of constant declarations, integers with pretty names. BTW, VB6 has the same problem with enums. To me, the whole point of having an enum is to express the fact that you have a specific, fixed range of values, *so the compiler can check that*. Arguing the importance of explaining such constraints to your compiler is lost on the typical C programmer. They just don’t believe in it.

  1. 1 Casting ints to enums in C# | Ask Programming & Technology Trackback on 1 November 2013 at 17:44
  2. 2 C# Cast Int to Enum Out of Range Trackback on 15 October 2015 at 8:09

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Follow me on Twitter



%d bloggers like this: