Hit enter after type your search item

C# Random class

The Random class of C# can be used for creating the practically usable random numbers like password generator. A few main points about the Random class are:

  • The Random class represents pseudo-number generator.
  • A mathematical algorithm is used for generating a random number.
  • Basically, Random class uses the modified version of Donald E. Knuth’s subtractive random number generator algorithm.
  • You may use the Random class after including the reference for the System namespace.

An example of generating a random number

In this example, five int (byte) numbers are generated randomly. First, a byte type array is declared with four elements. Then, a random object is created and NextBytes method of the Random class is used for generating four random numbers.

Finally, we used a foreach loop to display the random numbers as follows:


The output as I executed this code:

c# random

The numbers should vary as you execute this code every time.

Using Next method for generating int random numbers within a range

The following example shows using the Next method of the Random class and generating random numbers based on provided ranges. For example, the first random number is generated between 1 – 100. The second is between 100 to 400 while the fourth is from 1000 to 10000.

The Code:


c# random_Next

The example of creating double type random numbers

The Random class also has a method NextDouble() that can be used for creating the random numbers with decimal points.

In the example below, we have an array of the double type with three elements. The NextDouble method of the Random class is used as follows:


c# random NextDouble

You may also use:

dbl_rand.NextDouble() + 1,

dbl_rand.NextDouble() – 2,

dbl_rand.NextDouble() + 3

That means you may also specify a number if you want to get the random number bigger or smaller.

An example of generating five random numbers within a range

The following example shows generating ten random numbers within the range of 1 and 1000. A for loop is used for that purpose as shown below:


The output as this code is executed:

c# random ten

Generating ten random floating numbers

This example shows generating ten floating random numbers by using the NextDouble() method in the for loop. The random numbers are within the range of 1 and 4:


c# random_ten_doble

 

This div height required for enabling the sticky sidebar