Generating Random Numbers in the .NET Framework using C#
Random numbers may be generated in the .NET Framework by making use of the Random class. This class may be instantiated using the following code:
//Create a new Random class in C#
Random RandomClass? = new Random();
Random Integers
Once the class has been instantiated, a random integer can be obtained by calling the Next method of the Random class:
//C#
int RandomNumber? = RandomClass?.Next();
The value of RandomNumber? will, therefore, be assigned a random whole number between 1 and 2,147,483,647.
In most coding situations, it is more desirable to create a random number within a certain size range. In this case, the Next method should be called with two arguments: the minimum value and the maximum value. For example, the following assigns RandomNumber? to a value that is greater or equal to 4 and less than 14:
//C#
int RandomNumber? = RandomClass?.Next(4, 14);
Note that an ArgumentOutOfRangeException? will be raised if the minimum value is larger than the maximum value.
It is also possible to specify just the maximum value using a different constructor. The following will return a return a random integer that is greater or equal to 0 and less than 14:
//C#
int RandomNumber? = RandomClass?.Next(14);
Again, an ArgumentOutOfRangeException? will be raised if the maximum value is smaller than 0.
Random Floating Point Numbers
As well as returning random integers, the Random class can also return floating point numbers. The NextDouble? method returns a random number as a Double. The random number's value is always greater or equal to 0.0, and less than 1.0:
//Create a random double using C#
double RandomNumber? = RandomClass?.NextDouble();
0 comments:
Post a Comment