Generating Random Numbers in C#
Syntax

Random()

Random(int Seed)

int Next()

int Next(int maxValue)

int Next(int minValue, int maxValue)
Parameters
Parameters  Details 

Seed  A value for generating random numbers. If not set, the default value is determined by the current system time. 
minValue  Generated numbers won't be smaller than this value. If not set, the default value is 0. 
maxValue  Generated numbers will be smaller than this value. If not set, the default value is Int32.MaxValue . 
return value  Returns a number with random value. 
Remarks
The random seed generated by the system isn't the same in every different run.
Seeds generated in the same time might be the same.
Create multiple random class with different seeds simultaneously
Two Random class created at the same time will have the same seed value.
Using System.Guid.NewGuid().GetHashCode()
can get a different seed even in the same time.
Another way to achieve different seeds is to use another Random
instance to retrieve the seed values.
This also makes it possible to control the result of all the Random
instances by setting only the seed value for the rndSeeds
. All the other instances will be deterministically derived from that single seed value.
Generate a number that is a percentage of a max value
A common need for random numbers it to generate a number that is X%
of some max value. this can be done by treating the result of NextDouble()
as a percentage:
Generate a random character
Generate a random letter between a
and z
by using the Next()
overload for a given range of numbers, then converting the resulting int
to a char
Generate a Random double
Generate a random number between 0 and 1.0. (not including 1.0)
Generate a random int
This example generates random values between 0 and 2147483647.
Generate a random int in a given range
Generate a random number between minValue
and maxValue  1
.
Generating the same sequence of random numbers over and over again
When creating Random
instances with the same seed, the same numbers will be generated.
Output: