Skip to content

[API Proposal]: System.Random.NextUInt64 #115681

Open
@VesperGarment

Description

@VesperGarment

Background and motivation

Could we add System.Random.NextUInt64() ? As far as I can tell the only way to get a UInt64 full of random bits is to use Random.NextBytes() to get 8 bytes and the BitConverter them. This feels kind of icky because the implementation appears to be based on getting a UInt64 at a time - everything else is written in terms of it. So having to call it through coded that checks sizes and spans and such is kind of silly.

API Proposal

namespace System;

public class Random
{
    public virtual ulong NextUInt64() { // no need to bother with minValue and maxValue.
        return _impl.NextUInt64();
    }
}

API Usage

// I believe this would then be the "best" way to generate a random bool (as the core random work gets a ulong at a time).

bool NextBool(this Random rnd) {
    var u = Random.Shared.NextUInt64();
    return u & 1 == 1;
}


### Alternative Designs

_No response_

### Risks

I can't really think of any. Perhaps would become less "correct" if underlying implementation ever changed to not be 64-bit word based. But that seems unlikely?

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.RuntimeuntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions