Generating random numbers in C# is quick and easy using Random class. It’s built-in functionality which allows to produce integers, doubles and bytes. In this article you can find examples how to use it.
The most basic usage is calling Next function without any parameters against an object of Random class. It returns a non-negative value, grater than or equal to 0 and less than maximum Int32 value (2147483647).
Next method is overloaded, so there are two more variants: accepting one or two parameters. Option with one parameter defines upper limit and option with two parameters defines both lower and upper limit. It’s important to mention that lower limit is a number which is included in the possible results, whilst upper limit is excluded.
Another function which is defined in Random class is NextDouble. It generates a random floating-point number, greater than or equal to 0.0 and less than 1.0. NextDouble is not overloaded, so there is no option to narrow down the range of possible result.
If you need random double that is greater than or equal to 1, it can be easily generated by combining Next with NextDouble.
Last function which we wanted to present here is NextBytes, which fills byte array with random numbers.
Please bear in mind, Random is pseudo-random number generator. The class is predictable and strictly relies on an initial seed value which is used to generate first number in a “random sequence”. As a result of what, if two Random objects are initiated with the same seed value, then every consecutive number generated by two separate objects will be the same. By default seed is calculated based on system clock, which means it is possible to have two or more objects with the same starting conditions (seeds).
Random constructor is overloaded, so that it is possible to initiate an object with custom seed value. That way, it’s easy to observe the predictable nature of Random class.
Example output of above code execution is:
Does it mean Random class is useless? Absolutely not. You just need to distinguish the use cases. It is fine to use pseudo-random generators where security is not a concern (for example when shuffling photos or songs). When security is important though (for example when generating passwords) then cryptographic random number generators should be taken into consideration. There is other built-in class which provide such functionality – it’s called RandomNumberGenerator.