Sunday, April 23, 2023

How to generate a random integer in C# ?

You can generate a random integer in C# using the 'Random' class in the 'System' namespace. Here's an example.
Random random = new Random();
int randomNumber = random.Next();
In the above example, we create a new 'Random' object and then call the 'Next()' method to generate a random integer. By default, the 'Next()' method returns a non-negative random integer. You can also pass arguments to the 'Next()' method to specify a range of values from which to generate the random integer, like this:
Random random = new Random();
int randomNumberInRange = random.Next(1, 101); // Generates a random integer between 1 and 100
In this example, we pass two arguments to the 'Next()' method to specify a range of values from 1 to 100, inclusive. The 'Next()' method returns a random integer within this range.

No comments:

Post a Comment