Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 53 / 68

Generating Random Numbers

In this lesson you will learn how to generate random numbers with the Random class in C#, so you can build things with an element of chance such as dice or rock-paper-scissors. This is for anyone searching for "C# Random how to use".

The Random class produces random numbers. Use it for dice rolls, raffles, and similar programs. The result changes every time you run it.

The sample code rolls a die from 1 to 6 with rnd.Next(1, 7) and picks one of "Rock", "Scissors", "Paper" at random with rnd.Next(choices.Length). Note that the second argument of Next() is exclusive - it means "below this value".

A common stumbling block for beginners is calling new Random() inside a loop, which can produce the same number repeatedly. Reuse a single Random instance instead.

In real-world development, you can fix a seed value when a test needs to reproduce the same sequence, and use the System.Security.Cryptography namespace when you need randomness that is harder to predict.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)