Generating Random Numbers with Random in C#

We can use Random class to generate a sequence of pseudorandom numbers. It can be useful for modeling, simulation or gaming applications.

We can use random class with two constructors

  1. Public Random()
  2. Public Random( int SeedValue)

Seed value is the starting point or value of the generated sequence, we can give the seed value otherwise Random() uses the system time to compute the seed value.

Example:

 Random RandomNumbers = new Random();
 string randomNumStr="";
 for (int i = 0; i < 5; i++)
   {
       randomNumStr = randomNumStr + " " + RandomNumbers.Next();
    }

You can see

value of randomNumStr: 1996035278 545350924 138404837 1162952561 28779640

  randomNumStr = "";
  for (int i = 0; i < 5; i++)
  {
        randomNumStr = randomNumStr + " " + RandomNumbers.Next(10);
   }

Value of randomNumStr: 7 6 6 5 3

 randomNumStr = "";
 for (int i = 0; i < 5; i++)
   {
       randomNumStr = randomNumStr + " " + RandomNumbers.Next(5,10);
    }

Value of randomNumStr:  7 7 5 9 7

Byte[] b = new Byte[10];
RandomNumbers.NextBytes(b);

We can see b has sequence of rendom numbers.

randomNumStr = "";
for (int i = 0; i < 5; i++)
    {
        randomNumStr = randomNumStr + " " + RandomNumbers.NextDouble().ToString("F2");
     }

Value of randomNumStr:  0.60 0.51 0.50 0.18 0.63

Random support these methods:

Next()Returns the next random number( between 0 to int maximum value
Next(int maxvalue)Returns the next random number between 0 to maxvalue
Next(int minvalue,int maxvalue)Returns the next random numbers between minvalue to maxvalue
NextBytes(byte[] buffer)Here byte is a sequence of random numbers

Each byte in the array will be between 0 to byte.maxval

NextDouble()Returns a random number between 0.0 and 1.0.
Sample()Returns a random number between 0.0 and 1.0.