Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there another way to test Enum bit fields?

When using Enums with bit fields:

   enum  ReallyBigEnum  { FirstChoice = 0x01, AnotherOption = 0x02 }
   ReallyBigEnum  flag = ReallyBigEnum.FirstChoice | ReallyBigEnum.AnotherOption;

the code used to test the bits is:

   if( (flag & ReallyBigEnum.AnotherOption) == ReallyBigEnum.AnotherOption ) { ... }

which seems verbose and error prone because of the need to repeat the bit being tested.

It would be nice if there were some way to say:

   if( flag.IsSet( ReallyBigEnum.AnotherOption ) ) { ... }

but Enums don't support instance methods. So, I tried a template function:

   class Enums
   {
      public static bool IsSet<T>( T flag, T bit ) { return (flag & bit) == bit; }
   }

but the code to test bits then looks like this:

   if( Enums.IsSet<ReallyBigEnum>( flag, ReallyBigEnum.AnotherOption ) ) { ... }

which is a lot to write. Then I tried to shorten it:

   class Enums
   {
      public static bool IsSet( int flag, int bit ) { return (flag & bit) == bit; }
   }

but then you have to cast each value to its base type like this:

   if( Enums.IsSet( (int)flag, (int)ReallyBigEnum.AnotherOption ) ) { ... }

which is also a pain to code and loses the benefit of type checking.

The same function could be written to use 'object' parameters, but then the object type and underlying base type would have to be tested.

So, I'm stuck with the standard, redundant way at the top.

Does anyone have other ideas on a clean, simple way of testing Enum bit fields?

Much Thanks.

like image 478
Chris C. Avatar asked Sep 16 '10 20:09

Chris C.


People also ask

What is a bit field enum?

A standard enumeration provides a list of named integer values. These values can be accessed using either the name or the associated value. Using the name rather than the value from within your program makes the code much easier to read and maintain.

Are bit fields portable?

Bit fields are portable, in the sense that they are a part of the C language as specified in the standard (C11 section 6.7. 2.1). Any compiler that fails to recognise code that uses bitfields is not standard-compliant.

Is array of bit fields allowed?

If the value is zero, the declaration has no declarator . Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not allowed. The optional declarator names the bit field. Bit fields can only be declared as part of a structure.

How does a Bitfield work?

A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected.


1 Answers

Up to .Net 3.5 this is your only option. In .Net 4.0 there is a HasFlag method on the enum.

like image 74
AxelEckenberger Avatar answered Oct 05 '22 16:10

AxelEckenberger