How to generate a random number in C#

Here’s a quick and dirty way to use Microsoft’s “Random” class for generating a random (or as you will soon find out, not-so-random) number.

Because I believe in code reuse, I started by creating a new function that would return the random number as an integer datatype.

static int RandomNumber(int min, int max)

{

Random random = new Random();

return random.Next(min, max);

}

The only things you have to pass to the function are the upper and lower boundaries that you want the random number to fall between.

int zip = RandomNumber(10000, 99999);

In the above example, a random number between 10000 and 99999 will be assigned to the “zip” variable.

As I stated above, the random number isn’t actually very random and, therefore, might not be a perfect fit for what your trying to use it for.  However, the Random class serves its purpose for quick data generation for application testing.

Happy coding!