CSharp - Essential Types Random class

Introduction

Random class generates a pseudorandom sequence of random bytes, integers, or doubles.

To use Random, instantiate it optionally with a seed for the random number series.

Using the same seed guarantees the same series of numbers.

Random r1 = new Random (1);
Random r2 = new Random (1);
Console.WriteLine (r1.Next (100) + ", " + r1.Next (100));      // 24, 11
Console.WriteLine (r2.Next (100) + ", " + r2.Next (100));      // 24, 11

Random seed uses the current system time as default value.

Calling Next(n) generates a random integer between 0 and n-1.

NextDouble generates a random double between 0 and 1.

NextBytes fills a byte array with random values.

To get a cryptographically strong random number, use the generator in the System.Security.Cryptography namespace.

var rand = System.Security.Cryptography.RandomNumberGenerator.Create();
byte[] bytes = new byte [32];
rand.GetBytes (bytes);       // Fill the byte array with random numbers.
//To obtain an integer, you must use BitConverter:
byte[] bytes = new byte [4];
rand.GetBytes (bytes);
int i = BitConverter.ToInt32 (bytes, 0);

Demo

using System;
class MainClass//from ww  w. jav a  2s  .c o  m
{
   public static void Main(string[] args)
   {
        Random r1 = new Random (1);
        Random r2 = new Random (1);
        Console.WriteLine (r1.Next (100) + ", " + r1.Next (100));      // 24, 11
        Console.WriteLine (r2.Next (100) + ", " + r2.Next (100));      // 24, 11

   }
}

Result