How to generate random numbers in C#?
How to generate random numbers in C#?
426
18-Aug-2023
Updated on 19-Aug-2023
Aryan Kumar
19-Aug-2023To generate random numbers in C#, you can use the
Random
class. TheRandom
class is a static class, which means that you do not need to create an instance of it. You can simply call its methods directly.The
Random
class has a number of methods for generating random numbers. The most commonly used method is theNext()
method. TheNext()
method takes two parameters: the minimum value and the maximum value. TheNext()
method will return a random number between the minimum value and the maximum value, inclusive.For example, the following code will generate a random number between 1 and 100:
C#
You can also use the
NextDouble()
method to generate a random number between 0 and 1.For example, the following code will generate a random number between 0 and 1:
C#
The
Random
class also has a number of other methods for generating random numbers. You can find more information about theRandom
class in the C# documentation.Here are some additional things to keep in mind when generating random numbers in C#:
Random
class uses a seed value to generate random numbers. The seed value is an integer that is used to initialize the random number generator. The same seed value will always generate the same sequence of random numbers.SetSeed()
method. TheSetSeed()
method takes an integer as its parameter.Random
class is not thread-safe. This means that you cannot use it to generate random numbers from multiple threads at the same time. If you need to generate random numbers from multiple threads, you should use a thread-safe random number generator.