Output The output looks random. I haven't run any tests of randomness on RNGCryptoServiceProvider or compared it to the Random type.
static void Main()
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
// Buffer storage.
byte data = new byte;
// Ten iterations.for (int i = 0; i < 10; i++)
// Fill buffer.
// Convert to int 32.
int value = BitConverter.ToInt32(data, 0);
Benchmark. I quantified the performance of RNGCryptoServiceProvider and Random. The code called Next() for Random. The objects were created outside of the inner loop.
Result It is clear from these results that you might end up with a slow program if you overuse RNGCryptoServiceProvider.
Time for one random int from RNGCryptoServiceProvider: 2796.19 ns
Time for one random int from Random: 9.30 ns
Discussion. So when should you use RNGCryptoServiceProvider? My expectation is that for most programs, Random is sufficient and preferable due to its simplicity.
But For important programs RNGCryptoServiceProvider is better because it is less prone to problems with its randomness.
Note The Random type does not use the RNGCryptoServiceProvider internally. The implementations are different.
Summary. We looked at the RNGCryptoServiceProvider type. With this type, you can fill byte arrays with random values. Then you can convert those byte arrays to integral types or use them directly.