SmallInjectorDemo/RandomHelper.cs
Holger Boerchers 5d38e038bb added comments
2018-08-12 20:21:51 +02:00

40 lines
1.2 KiB
C#

using System;
using System.Security.Cryptography;
namespace SmallInjectorDemo
{
/// <summary>
/// Static helper class for generating random numbers.
/// </summary>
public static class RandomHelper
{
/// <summary>
/// Return cryptographic stable random integer.
/// </summary>
/// <param name="min">Lower border of result.</param>
/// <param name="max">Upper border of result.</param>
/// <returns>Random integer.</returns>
public static int NewRandomInteger(int min, int max)
{
// The random number provider.
using (var rand = new RNGCryptoServiceProvider())
{
uint scale = uint.MaxValue;
while (scale == uint.MaxValue)
{
// Get four random bytes.
var four_bytes = new byte[4];
rand.GetBytes(four_bytes);
// Convert that into an uint.
scale = BitConverter.ToUInt32(four_bytes, 0);
}
// Add min to the scaled difference between max and min.
return (int)(min + (max - min) *
(scale / (double)uint.MaxValue));
}
}
}
}