Sentry Answers>C#>

Generate a random integer in C#

Generate a random integer in C#

David Y.

The ProblemJump To Solution

How do I generate a random integer in C#?

The Solution

We can generate pseudorandom numbers using C#‘s System.Random class. For example:

Click to Copy
Random rng = new Random(); int rand1 = rng.Next(100); // number between 0 and 99

We can also specify a lower bound for generated numbers:

Click to Copy
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:

Click to Copy
var randomBytes = new byte[4]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(randomBytes); uint trueRandom = BitConverter.ToUInt32(randomBytes, 0); }
  • SentryC# Error and Performance Monitoring
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

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.

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