Generate a random integer in C#

David Y.

The Problem

How do I generate a random integer in C#?

The Solution

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); }

Loved by over 4 million developers and more than 90,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.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.