Skip to content

[API Proposal]: Random.Next<T> #75431

Closed

Description

@stephentoub

Background and motivation

Now that we have the generic math interfaces, we should be able to write a method for generating a random value that can work with any T where T implements the appropriate interface.

API Proposal

namespace System;

public partial class Random
{
    ...

    public T NextInteger<T>() where T : System.Numerics.IBinaryInteger<T>, System.Numerics.IMinMaxValue<T>;
    public T NextInteger<T>(T maxValue) where T : System.Numerics.IBinaryInteger<T>;
    public T NextInteger<T>(T minValue, T maxValue) where T : System.Numerics.IBinaryInteger<T>;

    public T NextFloat<T>() where T : IBinaryFloatingPointIeee754<T>
}

API Usage

Random r = new Random();
Int128 value = r.NextInteger<Int128>();

Alternative Designs

  • Naming: NextInteger vs Next, NextFloat vs ?

Risks

No response

Activity

  1. added
    api-suggestion
    on Sep 12, 2022
  2. added this to the 8.0.0 milestone on Sep 12, 2022
  3. danmoseley commented on Sep 12, 2022

    @danmoseley
    Contributor

    The range used for NextDouble is 0.0 to 1.0; for a floating-point API, we'd presumably want to map to the same range?

    Same for NextSingle() so I think so.

    It might be interesting to have a quick look at what random methods other stacks expose.

  4. DrkWzrd commented on Sep 12, 2022

    @DrkWzrd

    The range used for NextDouble is 0.0 to 1.0; for a floating-point API, we'd presumably want to map to the same range?

    Same for NextSingle() so I think so.

    It might be interesting to have a quick look at what random methods other stacks expose.

    Humbly I leave here my (not well written) random utilities I use when I need to seed to test something. As example of some useful methods or generics could be integrated

    public static class RandomExtensions
    {
        public static bool CoinToss(this Random rng)
        {
            return CoinToss(rng, .5);
        }
    
        public static bool CoinToss(this Random rng, double zeroWeight)
        {
            return rng.NextDouble() >= zeroWeight;
        }
    
        public static byte NextByte(this Random rng)
        {
            return (byte)rng.Next(byte.MinValue, byte.MaxValue + 1);
        }
    
        public static byte NextByte(this Random rng, byte min, byte max)
        {
            return (byte)rng.Next(min, max);
        }
    
        public static sbyte NextSbyte(this Random rng)
        {
            return (sbyte)rng.Next(sbyte.MinValue, sbyte.MaxValue + 1);
        }
    
        public static sbyte NextSbyte(this Random rng, sbyte min, sbyte max)
        {
            return (sbyte)rng.Next(min, max);
        }
    
        public static DateTime NextDateTime(this Random rng)
        {
            return NextDateTime(rng, DateTime.MinValue, DateTime.MaxValue);
        }
    
        public static DateTime NextDateTime(this Random rng, DateTime maxValue)
        {
            return NextDateTime(rng, DateTime.MinValue, maxValue);
        }
    
        public static DateTime NextDateTime(this Random rng, DateTime minValue, DateTime maxValue)
        {
            if (minValue >= maxValue) throw new ArgumentOutOfRangeException(nameof(minValue));
            var nextLong = rng.NextLong(minValue.Ticks, maxValue.Ticks);
            return new DateTime(nextLong);
        }
    
        public static DateOnly NextDate(this Random rng)
        {
            return NextDate(rng, DateOnly.MinValue, DateOnly.MaxValue);
        }
    
        public static DateOnly NextDate(this Random rng, DateOnly maxValue)
        {
            return NextDate(rng, DateOnly.MinValue, maxValue);
        }
    
        public static DateOnly NextDate(this Random rng, DateOnly minValue, DateOnly maxValue)
        {
            if (minValue >= maxValue) throw new ArgumentOutOfRangeException(nameof(minValue));
            var nextDay = rng.Next(minValue.DayNumber, maxValue.DayNumber);
            return DateOnly.FromDayNumber(nextDay);
        }
    
        public static TimeOnly NextTime(this Random rng)
        {
            return NextTime(rng, TimeOnly.MinValue, TimeOnly.MaxValue);
        }
    
        public static TimeOnly NextTime(this Random rng, TimeOnly maxValue)
        {
            return NextTime(rng, TimeOnly.MinValue, maxValue);
        }
    
        public static TimeOnly NextTime(this Random rng, TimeOnly minValue, TimeOnly maxValue)
        {
            if (minValue >= maxValue) throw new ArgumentOutOfRangeException(nameof(minValue));
            var nextLong = rng.NextLong(minValue.Ticks, maxValue.Ticks);
            return new TimeOnly(nextLong);
        }
    
        public static double NextDouble(this Random rng, double minValue, double maxValue)
        {
            return minValue + rng.NextDouble() * (maxValue - minValue);
        }
    
        public static long NextLong(this Random rng)
        {
            return NextLong(rng, 0, long.MaxValue);
        }
    
        public static long NextLong(this Random rng, long maxValue)
        {
            return NextLong(rng, 0, maxValue);
        }
    
        public static long NextLong(this Random rng, long minValue, long maxValue)
        {
            if (minValue >= maxValue)
                throw new ArgumentOutOfRangeException(nameof(minValue));
    
            //Working with ulong so that modulo works correctly with values > long.MaxValue
            var uRange = (ulong)(maxValue - minValue);
    
            //Prevent a modolo bias; see https://stackoverflow.com/a/10984975/238419
            //for more information.
            //In the worst case, the expected number of calls is 2 (though usually it's
            //much closer to 1) so this loop doesn't really hurt performance at all.
            ulong ulongRand;
            var buf = (stackalloc byte[8]);
            do
            {
                rng.NextBytes(buf);
                ulongRand = (ulong)BitConverter.ToInt64(buf);
            } while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange);
    
            return (long)(ulongRand % uRange) + minValue;
        }
    
        public static char NextChar(this Random rng)
        {
            return NextChar(rng, char.MinValue, char.MaxValue);
        }
    
        public static char NextChar(this Random rng, char maxValue)
        {
            return NextChar(rng, char.MinValue, maxValue);
        }
    
        public static char NextChar(this Random rng, char minValue, char maxValue)
        {
            if (minValue >= maxValue) 
                throw new ArgumentOutOfRangeException(nameof(minValue));
    
            int min = minValue;
            int max = maxValue;
            return (char)rng.Next(min, max);
        }
    
        public static string NextString(this Random rng, int length)
        {
            return NextString(rng, length, char.MinValue, char.MaxValue);
        }
    
        public static string NextString(this Random rng, int length, char maxValue)
        {
            return NextString(rng, length, char.MinValue, maxValue);
        }
    
        public static string NextString(this Random rng, int length, char minValue, char maxValue)
        {
            if (length < 0) 
                throw new ArgumentOutOfRangeException(nameof(length));
    
            var strSpan = (stackalloc char[length]);
    
            for (int i = 0; i < length; i++)
            {
                strSpan[i] = NextChar(rng, minValue, maxValue);
            }
            return strSpan.ToString();
        }
    }
  5. hopperpl commented on Sep 12, 2022

    @hopperpl

    is maxValue inclusive or exclusive? minValue respectively.

  6. stephentoub commented on Sep 12, 2022

    @stephentoub
    MemberAuthor

    In the existing APIs, minValue is inclusive and maxValue is exclusive. This is using the same naming as the existing overloads and would have the same semantics as the existing overloads.

  7. hopperpl commented on Sep 12, 2022

    @hopperpl

    then it should be noted that way...

    • because Next<T>(T.MinValue, T.MaxValue) will not be the same as Next<T>()
    • also Next<T>(0, T.MaxValue + 1) will not be possible (assuming T is a signed variant)... if the goal is to have any value of the positive range (of a signed T variant)

    I'm not against it, but it has to be clearly stated, I fell into that pitfall many times. The documentation mentions it for the current int implementation in a small remark. For example Next<byte>() can never return 255.

    I would on a personal note as this is a new implementation without backward compatibility ...

    • have Next<T>() return the full range of T
    • have Next<T>(T minInclusive, T maxInclusive) return a complete range -- or maxExclusive but have the parameter properly named -- problem with exclusive is still no full positive range possible
    • and when T is a floating point number default to T.Zero and T.One (inclusive)

    if default Next<float>() would not include 1 then the random value is not usable for the scenarios I use random float numbers.

    Oh, I forgot to mention, it is easy to turn inclusive to exclusive by subtracting 1 or Epsilon, but it is not possible to do the opposite, as T.MaxValue is the maximum value and nothing can be bigger.

  8. Clockwork-Muse commented on Sep 12, 2022

    @Clockwork-Muse
    Contributor

    For example Next<byte>() can never return 255.

    Which can cause slight bias to results downstream, as I brought up in #41457 .

    if default Next<float>() would not include 1 then the random value is not usable for the scenarios I use random float numbers.

    .... what are these scenarios?

  9. hopperpl commented on Sep 12, 2022

    @hopperpl

    .... what are these scenarios?

    raytracing, (audio) signal processing, field density, math, geometry, anything that is too complex to completely calculate... you use a randomization of a normalized set (so 0 to 1) and then calculate until you have enough result values... as the calculation will theoretically go on forever... if the 1 is missing as a random value, one "edge" will be "not sharp"

    If you have a large input set, then it doesn't make a difference as by rounding you hit the edge, but sometimes you have a 3 dimensional set or a 4 dimensional set with a very "thin" dimension, for example depth or color/hue (4th dimension). Or you have a reduced data set and the last thing you want is to add a special randomizer for such special cases.

    Normalization is usually done with a range of 0 to 1 inclusive. Or -1 to +1 inclusive. The left x-coordinate is 0, the right x-coordinate is 1. Or you have a line from A to B and use a random number to find any point between A and B. But you want A and B both included. A line segment between 2 points includes both points. Normalized, to find A you use 0 and to find B you use 1. In float-color (0,0,0) is Black and (1,1,1) is White, (0.5,0.5,0.5) is Gray etc. The 1 is always part of the set.

  10. aloraman commented on Sep 12, 2022

    @aloraman

    Thoughts on API shape

    I don't think having the same random API for all numeric types is a good idea. Integer numbers and floating-point numbers have different behaviors and expectations. Single generic API for all of them would have very weird behavior. The very core of RNG is producing sequence of uniformly distributed byte values, other methods produce values of specific types from these byte sequences. With that in mind we can look at differences in numeric types:

    • Binary integers (from System.Byte to System.Int64, signed and unsigned) have values that are uniformly distributed. Every interval also has uniformly distributed values. So, producing a binary integer from byte sequence is almost as easy as filling the memory span with these bytes (there are tricks to support Next(min, max), more on that later). When users call Random.Next<TBinaryInteger>(min, max), they expect to receive uniformly distributed values.
    • IEEE754 floating-point numbers (System.Half, System.Single, System.Double) have values that are not uniformly distributed. Some intervals have uniformly distributed numbers, some haven't - it depends on whether only mantissa is changing, or there's a change in value of exponent as well. If we simply fill a memory span with random bytes we won't get a uniform distribution, we'll get a distribution with logarithmic density, which behaves very counter-intuitively. There is a way to produce uniformly distributed values in the interval [0.0; 1.0) utilizing dyadic rationals and the specific size of mantissa, which is used in current implementation. Maybe we can define Next(max) and Next(min, max) for floating point numbers from Next(0, 1) via linear transformation, but I'm not sure if that's a good idea - precision loss can skew the distribution.
    • Non-IEEE754 floating-point numbers (System.Decimal) is its own can of worms, I can't say a lot about it, maybe have specific API for decimals? With a way to pass a specific required precision.
    • Other new numeric types - Here be dragons! What should Random.Next<BigInteger>() produce? Should Random.Next<Complex>() produce values from full Complex plane or from unit circle?

    Proposed API shape

    public class Random
    {
        public T Next<T>() where T : IBinaryInteger<T>; // produces values from [T.Zero;T.MaxValue)
        public T Next<T>(T maxValue) where T : IBinaryInteger<T>; // produces values from [T.Zero;maxValue)
        public T Next<T>(T minValue, T maxValue) where T : IBinaryInteger<T>; // produces values from [minValue;maxValue)
        public T NextFloat<T>() where T:IBinaryFloatingPointIeee754<T> // produces values from [0.0;1.0), can't have the same name :(
    }    

    Basically, Next<T> for binary integers should produce values in the same range as existing methods, i.e., Random.Next<System.Int32>() should behave the same way Random.Next() behaves now.

    Other questions

    1. To implement Next(min, max) for binary integers current implementation uses the range hit test, utilizing Log2Ceiling. Do we have Log2Ceiling for every binary integer type? Or Log2 + PopCount?
    2. To produce [0.0; 1.0) uniform distribution current implementation uses dyadic rationals, utilizing type-specific bit-twiddling. Do we have required constants to implement this bit-twiddling in a generic way?

    P.S. Maybe it is useful to provide raw span filling method in API, e.g.:

    public class Random
    {
        public void Fill<T>(ref T storage) where T: unmanaged;
    }
  11. koszeggy commented on Feb 2, 2023

    @koszeggy
    Contributor

    Before adding newer and newer members to Random please consider the API suggestion I proposed in #60549.

    ℹ️ Background Info: The problem is that since C# 2.0 adding new virtual members to Random is a breaking change for derived Random classes because until the creator of the derived class can release a new version of their library the non-overridden new methods will fall back to the legacy Random behavior.

    Breaking Issue Example:

    The last good example is the introduction of NextInt64 and NextSingle methods. I have a SecureRandom class (among others). When .NET 6 was released with the new NextInt64 overloads, and before I could release a new version with the new overloads (or even after, if someone targeted .NET 6 without upgrading my libraries), SecureRandom.NextInt64 failed to return cryptographically secure results.

    Even worse (though the issue stands also without this addendum), I actually have a lot of extension methods, for Random, including some NextInt64 overloads that returned secure results before .NET 6 but when Random.NextInt64 has been introduced, it was not the case anymore until I upgraded my libraries.

    Possible Solutions:

    A. Instead of new Random members please introduce new extension methods that rely on the already existing members of any Random implementation (eg. NextBytes). Just like @DrkWzrd, I also offer my RandomExtensions for any possible help/inspiration. Here is a living online example as well.

    B. As I proposed in #60549, make it possible for a derived implementation to call a protected base constructor that uses an implementation where all virtual members rely on the Sample method as it was in C# 1.x. This not just prevents unnecessary seed initialization in base but also makes the possible new members forward compatible. The non-overridden members will maybe just be a little less optimized until the library is upgraded but will not fall back to the legacy implementation. I actually even prepared a pull request, in which I followed @GrabYourPitchforks' API review comments, but then unfortunately @stephentoub thought this API was not necessary after all. But now that we face new Random methods again and the same issues can be expected I kindly ask you to reconsider this statement.

    Disclaimer:

    This API proposal does not indicate the new Next<T> methods as virtual ones. If they are really non-virtual, then maybe my concerns are not that relevant in this particular case. Still, it would be really helpful to consider my proposal as it addresses the unnecessary allocations issue as well.


    Correction: I remembered incorrectly: The non-derived compatible implementation of the new NextInt64 method falled back to use multiple Next caused only a performance issue for my SecureRandom class but did not affect security. Meaning, my proposed API is no longer needed to implemented before this proposal. It would be only a solution for the unnecessary allocations and slow instantiation, which an independent issue from the new virtual methods. I apologize for creating an unnecessary noise in this issue.

  12. stephentoub commented on Feb 2, 2023

    @stephentoub
    MemberAuthor

    because until the creator of the derived class can release a new version of their library the non-overridden new method will fall back to the legacy Random behavior.

    Any new virtuals that are added delegate to an existing abstract/virtual on the type. In the case of the NextInt64 you mentioned, for example, it would delegate to the existing virtual Next(int), calling a derived type's implementation if it existed. So I'm not sure what you mean about it falling back to legacy behavior.

  13. tannergooding commented on Feb 2, 2023

    @tannergooding
    Member

    We have also not historically considered adding new virtual members to be a breaking change. That is exactly how we have to version types (otherwise we'd end up with RandomEx, RandomV5, etc) and we have nearly always reserved the right to extend our types with additional functionality where appropriate.

  14. 29 remaining items

  15. vladd commented on Mar 23, 2026

    @vladd

    But what should be the canonical way to obtain a random number from the whole range, including MaxValue? Switching to a bigger size? NextBytes()?

  16. bartonjs commented on Mar 30, 2026

    @bartonjs
    Member

    I feel like I tried something like this from the "batched random" proposal (it ended up with lots of type overloads, and the API Review feedback was "try to make it generic"), and the problem is that IBinaryInteger just says that the value is importable/exportable and it's based on powers of two. It makes no guarantee that the bit pattern of a number that can convert to/from an Int32 value of 2 looks similar to an Int32 with a value of 4.

    e.g. imagine an 8-bit number that stores the value of the index into a lookup table for randomized values 0..255 (this is me making a "stop trying to think of an esoteric math function and just say 'mapping table'" timebox limiter), but the math functions all work on the mapped-value rather than the index value.

    So, Next(0b0000_0010 (113), 0b0000_0001 (212)) has very unclear behaviors. From a bitwise perspective, max is less than min, but from a value perspective it's bigger, but the only way that I can think of to generate things by flipping bits is (max2 = max - min) and random 0..max2, based on the bit represenation of max2. But that, for my IBinaryInteger here, makes no sense.

    Now, we can always document "this is what it does, if your number type does numbers differently than Int32/UInt32, well, sorry, it's gibberish..." but I didn't feel like that would fly in a System.Security namespace. Maybe we're more relaxed for System.Random.

  17. kevincathcart-cas commented on Apr 14, 2026

    @kevincathcart-cas

    I feel like I tried something like this from the "batched random" proposal (it ended up with lots of type overloads, and the API Review feedback was "try to make it generic"), and the problem is that IBinaryInteger just says that the value is importable/exportable and it's based on powers of two. It makes no guarantee that the bit pattern of a number that can convert to/from an Int32 value of 2 looks similar to an Int32 with a value of 4.

    IBinaryInteger<TSelf>.ReadLittleEndian is not documented as importing the internal format of the number, but is currently documented as always importing a little endian twos complement number. This would imply (not documented!) that the WriteLittleEndian must output in that format, otherwise a round trip would change the number. Random certainly can handle making buffers in that format between two values for importing. So either the documentation for that method is wrong, or this should work.

    However, if the documentation is correct, then this does mean that the interface does not support exporting the number its its native format, which means that if we had a type documented to be stored in some other format like ones compliment or signed magnitude, then for example Toub's IBinaryInteger<TSelf>.ReverseBits proposal (#125879)'s DIM would reverse bits in the two's complement representation of an arbitrary IBinaryInteger, not its documented encoding, since the DIM literally would have no way of doing that.

  18. bartonjs commented on Apr 20, 2026

    @bartonjs
    Member

    Random certainly can handle making buffers in that format between two values for importing.

    Yeah, random can make a twos-complement binary representation, but it can't know that the value imported by 0b0010 is necessarily less than the value imported by 0b0100. (Maybe somewhere we have that as an explicit expectation, but I don't know that we assert that x > y implies T.CreateChecked(x) > T.CreateChecked(y), or even that T(x) is not less than T(y)).

    It could be "solved" with a doc comment, and I don't have a real-world example off the top of my head, but I believe that assumption is being made by this proposal, and it's mostly based on common sense more than it is any notion of "rules".

  19. tannergooding commented on Apr 21, 2026

    @tannergooding
    Member

    This would imply (not documented!)

    This would be an oversight in the documentation, yes. It is explicitly read/written as a two's complement binary integer to ensure roundtripping and serialization can occur. It does not have to be the shortest 2's complement integer.

    but it can't know that the value imported by 0b0010 is necessarily less than the value imported by 0b0100

    This shouldn't really be true. The data read is strictly a two's complement integer and so 0b0010 is strictly 2 and 0b0100 is strictly 4. It is then required to throw an OverflowException if the value is not representable as the target type.

    The trickiness comes in that someone could have a binary integer that works a bit like floating-point where it saturates and rounds to the nearest representable values, such a type would have implicit bias introduced for its Random implementation if we assume normal distribution.

    Such a risk is probably acceptable given such types are likely rare and can override with their own behavior that is suitable for their type.

  20. bartonjs commented on Apr 21, 2026

    @bartonjs
    Member

    Video

    • Even though the existing "Next" is for Int32, the consensus was to use "NextInteger" in case a different generic version of Next was invented later.
    • We discussed virtual or not, and feel that not-virtual is better (at least for now)
    • Renamed NextFloat to NextBinaryFloat to leave space for NextDecimalFloat and also to avoid having NextSingle and NextFloat, with the latter not being the same as the float keyword.
    • The parameterless NextInteger should be capable of returning the MaxValue value (full range).
    namespace System;
    
    public partial class Random
    {
        // This version should be capable of returning maxValue, not defer to NextInteger(T.MaxValue)
        public T NextInteger<T>() where T : System.Numerics.IBinaryInteger<T>, System.Numerics.IMinMaxValue<T>;
    
        public T NextInteger<T>(T maxValue) where T : System.Numerics.IBinaryInteger<T>;
        public T NextInteger<T>(T minValue, T maxValue) where T : System.Numerics.IBinaryInteger<T>;
    
        public T NextBinaryFloat<T>() where T : IBinaryFloatingPointIeee754<T>
    }
  21. added
    api-approved
    and removed
    api-ready-for-review
    on Apr 21, 2026
  22. kevincathcart-cas commented on Apr 21, 2026

    @kevincathcart-cas

    The parameterless NextInteger should be capable of returning the MaxValue value (full range).

    This works, but it isn't consistent with Next(), which wasn't discussed explicitly in review.

    Also this is always 0 to Something, so for signed values, there is still no direct way to get the whole range, although or unsigned values including maxValue does give the full range.

  23. stephentoub commented on Apr 27, 2026

    @stephentoub
    MemberAuthor

    This works, but it isn't consistent with Next(), which wasn't discussed explicitly in review.

    It was discussed at ~1:17:00.

  24. added
    in-pr
    on Apr 27, 2026
  25. locked and limited conversation to collaborators on Jun 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Numericsin-pr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions