typestar

Random.Shared in C#

The ready-made generator, no seeding ceremony.

// Random.Shared is the ready-made, thread-safe generator
var roll = Random.Shared.Next(1, 7);
Console.WriteLine($"rolled {roll}");

var sample = Enumerable.Range(0, 5)
    .Select(_ => Random.Shared.NextDouble())
    .ToList();
Console.WriteLine(sample.Average() is > 0 and < 1);

var options = new[] { "rock", "paper", "scissors" };
Console.WriteLine(options[Random.Shared.Next(options.Length)]);

How it works

  1. Random.Shared is thread-safe and already constructed.
  2. Next(1, 7) rolls a die — the upper bound is exclusive.
  3. NextDouble fills statistical sampling; indexing picks an option.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
390
Tokens
101
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 3 of 3 in Diagnostics & environment, step 15 of 17 in The .NET library.

← Previous Next →