C# Get random items or numbers

Date: 2021-11-19
using System.Security.Cryptography;

public class RandomHelper
{
    public static double GetRandomDouble()
    {
        var bytes = new byte[8];
        RandomNumberGenerator.Fill(bytes);
        var randomUInt64 = BitConverter.ToUInt64(bytes, 0);
        // Schaal naar [0.0, 1.0) door te delen door (ulong.MaxValue + 1.0)
        return randomUInt64 / ((double)ulong.MaxValue + 1.0);
    }

    public static string GetRandomChar(string charString) => $"{GetRandom(charString.ToCharArray())}";

    public static T GetRandom<T>(params T[] values)
    {
        if (values == null || values.Length == 0)
            throw new ArgumentException("The values array cannot be null or empty.", nameof(values));
        return values[GetRandomInt(values.Length)];
    }

    public static int GetRandomInt(int maximum) => GetRandomInt(0, maximum);
    public static int GetRandomInt(int minimum, int maximum)
    {
        if (minimum == maximum) return minimum;
        if (minimum > maximum)
            throw new ArgumentOutOfRangeException(nameof(minimum), "Minimum should be less than or equal to maximum.");
        return RandomNumberGenerator.GetInt32(minimum, maximum);
    }

    public static double GetRandomDouble(double minimum, double maximum)
    {
        if (minimum == maximum) return minimum;
        if (minimum > maximum)
            throw new ArgumentOutOfRangeException(nameof(minimum), "Minimum should be less than or equal to maximum.");

        return GetRandomDouble() * (maximum - minimum) + minimum;
    }
}
56580cookie-checkC# Get random items or numbers