Note that there are some explanatory texts on larger screens.

plurals
  1. POCasting ints to enums in C#
    primarykey
    data
    text
    <p>There is something that I cannot understand in C#. You can cast an out-of-range <code>int</code> into an <code>enum</code> and the compiler does not flinch. Imagine this <code>enum</code>:</p> <pre><code>enum Colour { Red = 1, Green = 2, Blue = 3 } </code></pre> <p>Now, if you write:</p> <pre><code>Colour eco; eco = (Colour)17; </code></pre> <p>The compiler thinks that’s fine. And the runtime, too. Uh?</p> <p>Why did the C# team decide to make this possible? This decision misses the point of using enums, I think, in scenarios like this:</p> <pre><code>void DoSomethingWithColour(Colour eco) { //do something to eco. } </code></pre> <p>In a strong-typed language like C#, I would like to assume that <code>eco</code> will always hold a legal <code>Colour</code> value. But this is not the case. A programmer could call my method with a value of 17 assigned to <code>eco</code> (as in previous code snippet), so the code in my method must not assume that <code>eco</code> holds a legal <code>Colour</code> value. I need to test for it explicitly and handle the exceptional values as I please. Why is this?</p> <p>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 <code>int</code> into an <code>enum</code>, if the <code>int</code> value is known at compile time. If not, the runtime should throw an exception at the assignment statement.</p> <p>What do you think? Is there any reason why this is so?</p> <p>(Note. This is a question <a href="http://neh2.wordpress.com/2004/12/13/casting-enums-into-ints/" rel="noreferrer">I posted ages ago on my blog</a> but got no informative response.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload