How can I generate a random integer in C#?
How can I generate a random integer in C#?
143
12-Jul-2023
Aryan Kumar
13-Jul-2023Sure, here is how you can generate a random integer in C#:
C#
This code first creates a
Random
object. TheRandom
object is used to generate random numbers.The code then generates a random integer between 0 and 100. The
Next()
method of theRandom
object is used to generate a random number. TheNext()
method takes a maximum value as a parameter. The maximum value is exclusive, so the random number will be between 0 and the maximum value - 1.Finally, the code prints the random integer to the console.
Here is an explanation of the code:
using
statement is used to import theSystem
namespace. TheSystem
namespace contains theRandom
class.Random
class is used to generate random numbers.Next()
method of theRandom
class is used to generate a random number.Console.WriteLine()
method is used to print a string to the console.