Saturday, June 22, 2013

How to Generate a Random Number within a range - C#

You can easily generate a random number within a specific range by using the Random class in .Net.

The random class defined in the .Net Framework class library provides functionality to generate random numbers. The constructors in the Random class have 2 overloaded forms. It takes in either no value or a seed value. The Random class has 3 public methods, Next, NextBytes and NextDouble.

The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0. The Next method has 3 overloaded forms and allows you to set the minimum and maximum range of the random number.

The following code returns a random number in a specific range (0 to 100):

var rand = new Random();
String myNumber = rand.Next(0, 100).ToString();

No comments :

Post a Comment