Generate random numbers

Posted by Techie Cocktail | 12:05 PM | , | 0 comments »

.Net provides an object called 'Random' to generate random numbers. It is contained in System namespace.

Using the Random object we can generate random integers, bytes and doubles. The Random object contains 3 methods called Next, NextBytes and NextDouble for this purpose. To use the object create an instance of the Random class and call its methods.


Random ranGen = new Random();


Methods

a. Next:
Takes an integer number as the maximum number and returns a random non-negative number less than the maximum number supplied.

int number = ranGen.Next(10);

b. NextBytes:
Takes the buffer of byte[] and fills the buffer elements with random byte numbers.

byte[] buffer = new byte[10];
ranGen.NextBytes(buffer);

foreach (byte bte in buffer)
{
Console.WriteLine(bte.ToString());
}


c. NextDouble:
Returns a random double between 0.0 and 1.0 value.

double number = ranGen.NextDouble();

0 comments