Skip to content

Instantly share code, notes, and snippets.

@dochoffiday
Last active September 30, 2021 15:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dochoffiday/50b9da0260fdd48b1dcccac5926c1c7a to your computer and use it in GitHub Desktop.
Save dochoffiday/50b9da0260fdd48b1dcccac5926c1c7a to your computer and use it in GitHub Desktop.
C# Random based on RandomNumberGenerator | source: https://www.eimagine.com/how-to-generate-better-random-numbers-in-c-net-2/
using System;
using System.Security.Cryptography;
namespace R
{
///<summary>
/// Represents a pseudo-random number generator, a device that produces random data.
///</summary>
public class Rando : RandomNumberGenerator
{
private static RandomNumberGenerator Rng = RandomNumberGenerator.Create();
///<summary>
/// Fills the elements of a specified array of bytes with random numbers.
///</summary>
///<param name="data">An array of bytes to contain random numbers.</param>
public override void GetBytes(byte[] data)
{
Rng.GetBytes(data);
}
///<summary>
/// Returns a random number between 0.0 and 1.0.
///</summary>
public double NextDouble()
{
byte[] b = new byte[4];
Rng.GetBytes(b);
return BitConverter.ToUInt32(b, 0) / ((double)UInt32.MaxValue + 1);
}
///<summary>
/// Returns a random number within the specified range.
///</summary>
///<param name="minValue">The inclusive lower bound of the random number returned.</param>
///<param name="maxValue">The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.</param>
public int Next(int minValue, int maxValue)
{
long range = (long)maxValue - minValue;
return (int)((long)Math.Floor(NextDouble() * range) + minValue);
}
///<summary>
/// Returns a nonnegative random number.
///</summary>
public int Next()
{
return Next(0, Int32.MaxValue);
}
///<summary>
/// Returns a nonnegative random number less than the specified maximum
///</summary>
///<param name="maxValue">The inclusive upper bound of the random number returned. maxValue must be greater than or equal 0</param>
public int Next(int maxValue)
{
return Next(0, maxValue);
}
}
}
@simen-wu
Copy link

simen-wu commented Dec 1, 2020

Thanks for sharing. How do you dispose Rng (RandomNumberGenerator implements IDisposable)?

@dochoffiday
Copy link
Author

@simen-wu, you could probably do something like this: https://stackoverflow.com/a/12126624/234132

@jamiehankins
Copy link

I don't understand the point of this class. You inherit from RandomNumberGenerator, but you also instantiate a static RandomNumberGenerator. Why? Why not just call base.GetBytes(byte[] data)?

It would make more sense to me if you made all of your methods static, which you could since they only use Rng.

No disrespect meant, by the way. I spend a good amount of time in glass houses myself. 😃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment