How to generate random int number in C#?

The Random class is used to create random numbers. (Pseudo-random that is of course.).

Example:

Random rnd = new Random();
int month = rnd.Next(1, 13);
// creates a number between 1 and 12

int dice = rnd.Next(1, 7);
// creates a number between 1 and 6

int card = rnd.Next(52);
// creates a number between 0 and 51

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s