Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Flags enums can be treated as a simple integral type in which each individual bit corresponds to one of the flagged values. You can exploit this property to convert the bit-flagged enum value into an array of booleans, and then dispatch the methods you care about from a correlated array of delegates. </p> <p><strong>EDIT:</strong> <em>We could certainly make this code more compact through the use of LINQ and some helper functions, but I think it's easier to understand in the less sophisticated form. This may be case where maintainability trumps elegance.</em></p> <p>Here's an example:</p> <pre><code>[Flags()]public enum CheckType { Form = 1, QueryString = 2, TempData = 4, } void PerformActions( CheckType c ) { // array of bits set in the parameter {c} bool[] actionMask = { false, false, false }; // array of delegates to the corresponding actions we can invoke... Action availableActions = { DoSomething, DoSomethingElse, DoAnotherThing }; // disassemble the flags into a array of booleans for( int i = 0; i &lt; actionMask.Length; i++ ) actionMask[i] = (c &amp; (1 &lt;&lt; i)) != 0; // for each set flag, dispatch the corresponding action method for( int actionIndex = 0; actionIndex &lt; actionMask.Length; actionIndex++ ) { if( actionMask[actionIndex]) availableActions[actionIndex](); // invoke the corresponding action } } </code></pre> <p>Alternatively, if the order in which you evaluate doesn't matter, here is simpler, clearer solution that works just as well. If order does matter, replace the bit-shifting operations with an array containing the flags in the order you want to evaluate them in:</p> <pre><code>int flagMask = 1 &lt;&lt; 31; // start with high-order bit... while( flagMask != 0 ) // loop terminates once all flags have been compared { // switch on only a single bit... switch( theCheckType &amp; flagMask ) { case CheckType.Form: DoSomething(/*Some type of collection is passed */); break; case CheckType.QueryString: DoSomethingElse(/*Some other type of collection is passed */); break; case CheckType.TempData DoWhatever(/*Some different type of collection is passed */); break; } flagMask &gt;&gt;= 1; // bit-shift the flag value one bit to the right } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload