Files
Common-VS2019/SacsStandardBase/Base/Helpers/SacsRandomHelper.cs
T
2021-05-05 15:36:28 +01:00

56 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Sarand.Net.Standard.Base.Helpers
{
//=======================================================================
public static class SacsRandomHelper
{
//-------------------------------------------------------------------
// Properties.
public static RandomNumberGenerator RandomNumberGenerator { get; } = RandomNumberGenerator.Create();
private static Random random;
public static Random Random { get { if (random == null) random = new Random(GetInt32(Int32.MaxValue)); return random; } }
public static void Fill(byte[] byteArray)
{
// ToDo RandomNumberGenerator.Fill(byteArray);
RandomNumberGenerator.GetBytes(byteArray);
}
//-------------------------------------------------------------------
/// <summary>
/// Generates a random integer between 0 (inclusive) and a specified exclusive upper
/// bound using a cryptographically strong random number generator.
/// </summary>
/// <param name="toExclusive">The exclusive upper bound of the random range.</param>
/// <returns>A random integer between 0 (inclusive) and toExclusive (exclusive).</returns>
/// <exception cref="ArgumentOutOfRangeException">The toExclusive parameter is less than or equal to 0.</exception>
public static int GetInt32(int toExclusive)
{
return RandomNumberGenerator.GetInt32(toExclusive);
//return Random.Next(toExclusive);
}
//-------------------------------------------------------------------
/// <summary>
/// Generates a random integer between a specified inclusive lower bound and a specified
/// exclusive upper bound using a cryptographically strong random number generator.
/// </summary>
/// <param name="fromInclusive">The inclusive lower bound of the random range.</param>
/// <param name="toExclusive">The exclusive upper bound of the random range.</param>
/// <returns>A random integer between fromInclusive (inclusive) and toExclusive (exclusive).</returns>
/// <exception cref="ArgumentOutOfRangeException">The toExclusive parameter is less than or equal to the fromInclusive parameter.</exception>
public static int GetInt32(int fromInclusive, int toExclusive)
{
return RandomNumberGenerator.GetInt32(fromInclusive, toExclusive);
//return Random.Next(fromInclusive, toExclusive);
}
//-------------------------------------------------------------------
}
//=======================================================================
}