Flags Enum

Imagine we have an enum:

enum BitField
ZeroBit = 1,
OneBit = 2,
TwoBit = 4,
ThreeBit = 8

I thought about syntactic sugar to simplify working with bits.
Consider the following:

BitField b = BitField.TwoBit | BitField.ThreeBit;

Testing bits:

// how about this sugar?
bool secondBitSet = b.TwoBit;
// instead of:
bool secondBitSet = (b & BitField.TwoBit) == BitField.TwoBit;

Setting bits:

// how about
b.TwoBit = true;
// instead of:
b |= BitField.TwoBit;

// Same for clearing and inverting bits:
b.TwoBit = false;
// or
b.TwoBit = !b.TwoBit;

If you like it, you can vote on Microsoft Connect: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=247537


matthew said...

// Same for clearing and inverting bits:
b.TwoBit = false;

what would this expression evaluate to if you placed it into an if ()?

It would be dangerous if it evaluated to bool (== -> = bugs).

The idea seems nice in general though

Kirill Osenkov said...

If such a thing were to be implemented, the behavior would probably be the same as in every other bool property. I agree that it would be dangerous when put in the if-statement, so I guess a warning would be nice if such an assignment is used in an expression context.

Anonymous said...

b.TwoBit = !b.TwoBit

This would'nt clear the bit: would simply toggle one state to another..