.NET: Why aren't Enum's Range/Value Checked?

后端 未结 2 1403
不思量自难忘°
不思量自难忘° 2021-02-14 18:56

This has always bugged me. Perhaps someone with some hardcore knowledge of .NET internals can explain it to me.

Suppose I define an enum as follows:

publ         


        
相关标签:
2条回答
  • 2021-02-14 19:15

    The issue was performance. It is quite simple to have a checked enum for normal enums such as Color

    enum Color {
      Red,
      Blue
    }
    

    The problem though is for enum's which are used as bit flags.

    enum Property {
      IsFirst = 0x1,
      IsDefault = 0x2,
      IsLastAccessed = 0x4
    }
    

    Having to do a bitwise check for every single integer which is converted to an Enum value was deemed to be too expensive. Hence the relaxed conversion to enum values.

    0 讨论(0)
  • 2021-02-14 19:21

    Range-checking has a potentially unnecessary cost. It's therefore reasonable to not perform it implicitly. As already mentioned, [Flags] require that no such checking takes place. If the runtime would check for the presence of [Flags], this would still incur a runtime penalty every time you perform a conversion.

    The only way around this would be for the compiler to be aware of the [Flags] attribute. I guess this wasn't done to reduce the amount of runtime knowledge hardcoded into the compiler.

    0 讨论(0)
提交回复
热议问题