Casting ints to enums in C#

前端 未结 12 2120
北荒
北荒 2020-12-05 02:30

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

12条回答
  •  遥遥无期
    2020-12-05 02:43

    When you define an enum you are essentially giving names to values (syntatic sugar if you will). When you cast 17 to Colour, you are storing a value for a Colour that has no name. As you probably know in the end it is just an int field anyways.

    This is akin to declaring an integer that would accept only values from 1 to 100; the only language I ever saw that supported this level of checking was CHILL.

提交回复
热议问题