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
Random.Sharedis thread-safe and already constructed.Next(1, 7)rolls a die — the upper bound is exclusive.NextDoublefills statistical sampling; indexing picks an option.
Keywords and builtins used here
andisnewvar
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.
Step 3 of 3 in Diagnostics & environment, step 15 of 17 in The .NET library.