Constraint enum type bit number RRS feed

  • Question

  • Dear All,

    How to constraint the bit number of enum?

    For example, if 4-bit(not greater than 0x0f) is constraint for DeviceClass below.

    Thanks and Best regards,


        public enum DeviceClass
            TV = (0x00),
            DVD = (0x01),
            AMP = (0x02),

    • Edited by E-John Tuesday, January 29, 2019 11:03 AM
    Tuesday, January 29, 2019 8:54 AM

All replies

  • Enums are not designed to constraint values. They can't, in fact, do that. Any integral value can be mapped to any enum type and there is nothing you can do about it.

    The purpose of an enum is to make it easier to provide well-defined values. It is a convenience to make code easier to write and read but in fact doesn't provide any additional security. Any code that relies on an enum should always validate the values provided make sense. To do that you can go a couple of ways. The correct way is to look for the specific values you support. For example if your implementation only supports the first 2 values then you should explicitly check for them.

    void Foo ( DeviceClass device )
       if (device != DeviceClass.TV && device != DeviceClass.DVD)
          throw new ArgumentOutOfRangeException("Bad device");

    Another approach is to use Enum.IsDefined. This methods takes a value and an enum type and verifies the value is in there. The problem with this approach is that having the value defined doesn't mean your code understands it. The most common example of this is when you write your code against an enum and then later a new value is added to the enumeration. If your code is using a switch/if/etc to identify the value then the fact that the value is now part of the enum doesn't change the fact that your code doesn't support it. So use IsDefined only when you don't actually care about the enum value.

    Michael Taylor

    Tuesday, January 29, 2019 3:01 PM
  • Maybe you can write and use a custom attribute like this:


    public enum DeviceClass


       TV = 0x00,

       DVD = 0x01,

       AMP = 0x02,

       . . .



    Then you can write a fragment that validates the enumerations from the current assemblies. Execute it at the beginning of your program or in a custom build step.

    Tuesday, January 29, 2019 9:10 PM