GCSE Link: 2.06 (Random Number Generation)

Random numbers are often used in games when the programmer wants an unknown element in the code.

In C# we use the Random class to generate random integers.

Example 1 shows how the Random class can be used to simulate rolling a die.

Example 1
Random r = new();
Console.WriteLine(r.Next(1, 7));

Note that unlike in Python, the upper bound is not included in the range of possible outputs in C#.



How would you simulate a coin toss in C#?

Random r = new();
Console.WriteLine(r.Next(0, 2) == 0 ? "Heads" : "Tails");