title: How can I get the number of elements of any variable of type set?
body: <p>AFAIK there's no built-in function for that. Searching the web I found this <a href="http://www.codenewsfast.com/cnf/article/0/permalink.art-ng53q107885" rel="noreferrer">function</a> and it works for me, but I prefer not to use it since it's assembly and I can't understand what it is doing. So I wrote this function that also works:</p>
  
  
  
  <pre class="lang-pascal prettyprint-override"><code>function Cardinality(const PSet: PByteArray;
    const SizeOfSet(*in bytes*): Integer): Integer;
  const
    Masks: array[0..7] of Byte = (1, 2, 4, 8, 16, 32, 64, 128);
  var
    I, J: Integer;
  begin
    Result := 0;
    for I := 0 to SizeOfSet - 1 do
      for J := 0 to 7 do
        if (PSet^[I] and Masks[J]) &gt; 0 then
          Inc(Result);
  end;
  </code></pre>
  
  <p>Now, I want to know if I can rely on this function? Or maybe there's a trick behind the set data type and that's why delphi doesn't have a built-in method for that.</p>
  
  <p>But <code>if</code> my function is reliable <code>then</code> how can I improve it to:</p>
  
  <ol>
  <li>Pass constants to it</li>
  <li>Do a type check and make sure that a set is passed to the function</li>
  <li>Pass the value instead of its address</li>
  <li>Get rid of <code>SizeOfSet</code> parameter</li>
  </ol>
  
  <p>I want to call it like <code>Cardinality(AnySet)</code> instead of <code>Cardinality(@AnySet, SizeOf(TAnySet))</code>.</p>
  
  <p>By the way, I need to compile this in both XE and XE5.</p>