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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.