title: Generic single flag enumeration for bitmask enums
body: <p>I'm working on a codebase with several bit flags enums which look something like this</p>
  
  <pre><code>public enum BitMask
  {
      None = 0,
  
      OptionA = 1 &lt;&lt; 0,
      OptionB = 1 &lt;&lt; 1,
  
      OptionAandB = OptionA | OptionB,
  
      All = ~0
  } 
  </code></pre>
  
  <p>I can iterate over all enum values using this </p>
  
  <pre><code>public IEnumerable&lt;T&gt; EnumValues&lt;T&gt;()
  {
      return Enum.GetValues(typeof(T)).Cast&lt;T&gt;();
  }
  </code></pre>
  
  <p>I'm looking for a generic way to iterate over single flag values only, in this case, <code>OptionA</code> and <code>OptionB</code>. <strong>Not</strong> <code>None</code>, <code>OptionAandB</code>, <code>All</code>. I can cast to <code>long</code> and detect single flags as they are a power of two, a quick search on here suggests this</p>
  
  <pre><code>public bool IsPowerOfTwo(long val)
  {
      return (val != 0) &amp;&amp; ((val &amp; (val-1)) == 0) ;
  }
  </code></pre>
  
  <p>Nongeneric version works fine</p>
  
  <pre><code>public IEnumerable&lt;BitMask&gt; SingleFlagBitMaskValues()
  {
      return Enum.GetValues(typeof(BitMask))
                 .Cast&lt;BitMask&gt;()
                 .Where(e =&gt; IsPowerOfTwo((long)e));
  }
  </code></pre>
  
  <p>But the generic version doesn't compile because it doesn't like the cast to <code>long</code></p>
  
  <pre><code>public IEnumerable&lt;TEnum&gt; SingleFlagEnumValues&lt;TEnum&gt;()
  {
      return Enum.GetValues(typeof(TEnum))
          .Cast&lt;TEnum&gt;()
          .Where(e =&gt; IsPowerOfTwo((long)e));
  }
  </code></pre>
  
  <p>Any way around this?</p>