title: Is Random.NextBytes biased?
body: <p>The .NET reference source shows <a href="http://referencesource.microsoft.com/#mscorlib/system/random.cs,04910e5e5c6c9a8b" rel="noreferrer">the implementation of <code>NextBytes()</code></a> as: </p>
  
  <pre><code>for (int i=0; i&lt;buffer.Length; i++)
  {
      buffer[i]=(byte)(InternalSample()%(Byte.MaxValue+1)); 
  }
  </code></pre>
  
  <p><code>InternalSample</code> provides a value in [0, int.MaxValue), as evidenced by it's doc comment and the fact that <code>Next()</code>, which is documented to return this range, simply calls <code>InternalSample</code>. </p>
  
  <p>My concern is that, since <code>InternalSample</code> can produce <code>int.MaxValue</code> different values, and that number is not evenly divisible by 256, then we should have some slight bias in the resulting bytes, with some values (in this case just 255) occurring less frequently than others.</p>
  
  <p>My question is:</p>
  
  <ol>
  <li>Is this analysis correct or is the method in fact unbiased?</li>
  <li>If the bias exists, is it strong enough to matter for any real application?</li>
  </ol>
  
  <p>FYI I know <code>Random</code> should not be used for cryptographic purposes; I'm thinking about it's valid use cases (e. g. simulations).</p>