David Y.
—How do I generate a random integer in C#?
We can generate pseudorandom numbers using C#‘s System.Random
class. For example:
Random rng = new Random(); int rand1 = rng.Next(100); // number between 0 and 99
We can also specify a lower bound for generated numbers:
int rand2 = rng.Next(10, 20); // number between 10 and 19
Note that the randomness generated by calling rng.Next
is only pseudorandom, not truly random. This is sufficient for applications where true randomness is not critical, such as games or visualizations, but should not be used for anything related to security.
To generate truly random numbers, we should use the RandomNumberGenerator
class from System.Security.Cryptography
. For example:
var randomBytes = new byte[4]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(randomBytes); uint trueRandom = BitConverter.ToUInt32(randomBytes, 0); }
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.