How do I generate a random integer in C#?

In C#, you can generate a random integer using the Random class from the System namespace. Here's an example of how you can generate a random integer within a specified range:

csharp

using System;

class Program
{
    static void Main()
    {
        // Create a Random object
        Random random = new Random();

        // Generate a random integer between 1 (inclusive) and 100 (exclusive)
        int randomNumber = random.Next(1, 101);

        Console.WriteLine("Random Number: " + randomNumber);
    }
}

In this example, we're using the Next() method of the Random class to generate a random integer within the range of 1 to 100 (inclusive of 1 and exclusive of 100).

Remember that you should create only one instance of the Random class and reuse it to generate random numbers. Creating multiple instances in quick succession can lead to getting the same sequence of random numbers due to the way the default seed is initialized.

If you need random numbers in various parts of your code, it's recommended to create a single instance of Random and use it throughout your application.

csharp

Random random = new Random();

int randomNumber1 = random.Next(1, 101);
int randomNumber2 = random.Next(1, 101);

Console.WriteLine("Random Number 1: " + randomNumber1);
Console.WriteLine("Random Number 2: " + randomNumber2);

This will ensure that the random numbers are generated using the same seed, reducing the likelihood of patterns or repetitions in the generated values.

Comments