Random generator in CSharp
In this article, we are dealing with Random in CSharp. In programming, it is common to have a random event in its program. Most programming languages offer a class that acts as a random number generator.
The best way to illustrate this is by means of a cube.
Example of a Random generator in CSharp
class Program
{
public static void Main(string[] args)
{
Random cube = new Random();
int pips;
for (int i = 0; i < 10; i++)
{
pips = cube.Next(1, 7);
Console.WriteLine(pips);
}
Console.Read();
}
}
}
In order to use the random generator, we need to create an object of the Random class and need to initialise it. Then we can do the following:
pips = cube.Next(1, 7);
The 1 in the parentheses stands for the smallest number of numbers from which a random one is to be determined. And the 7 the boundary. Although we only want to have values up to 6, we have to specify the 7, so the next larger number.
The For loop I have now used here to get 10 values and show that it is really a Random generator.
There is also the possibility to get even more random values, with nextDouble e.g. . For details on the Random class, I can also recommend the documentation here.